package com.lzx.iteam;

import android.app.*;
import android.content.*;
import android.content.pm.PackageManager;
import android.content.res.*;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.*;
import android.graphics.drawable.shapes.RoundRectShape;
import android.media.AudioManager;
import android.os.*;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.*;
import android.widget.*;
import com.lzx.iteam.adapter.*;
import com.lzx.iteam.bean.*;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.contactssearch.ResultListManager;
import com.lzx.iteam.contactssearch.conversion.PinyinSearch;
import com.lzx.iteam.contactssearch.conversion.Addressbook.Person;
import com.lzx.iteam.contactssearch.conversion.PinyinSearch.ContactInfoNode;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudContactsDB;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.skin.GetSkinResource;
import com.lzx.iteam.task.UpLoadContactsTask;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.*;
import io.rong.imageloader.core.ImageLoader;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

import static com.lzx.iteam.CloudDialerActivity.ListStatus.ENUM_SHOW_CLOUD_CONTACT;

/**
 * 主界面
 *
 * @author hfx_lk
 *         setupShakeListener()方法为竖向键盘的方法，暂时注释掉
 */
public class CloudDialerActivity extends FragmentActivity implements View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener {
    private Context mContext;
    private AllDialogUtil mDialogUtil;
    public PreferenceUtil mPreferenceUtil;
    public static CloudDialerActivity instance;
    //============================键盘界面===========================//
    private boolean mKeypadAtRight = false; // 默认情况下keypad在左边

    private ImageView mHelpSlipKey, mHelpStructureAdd;
    public ImageView mHelpStructureEdit;
    public LinearLayout mKeyBoardMainContainer;
    private TextView mainTitle;
    //批量选择标题部分
    private LinearLayout mTabSelectAll, mLayoutSelectAll;
    private RelativeLayout mTitleBarSelectMode;
    private RelativeLayout mTitleBarNormalMode;
    private TextView mBtnSend;
    private TextView mBtnCancel;
    private TextView mBatchOperitonTitle;
    private TwiceTextChoiceView mShowModleChiceView;
    private LinearLayout mBatchOpertionLayout;
    private Dialog mDialog;
    private TextView mNull;
    private View leftShadowView;
    private View rightShadowView;
    private GradientDrawable leftShadow;
    private GradientDrawable rightShadow;
    private View horizonShadowView;
    private GradientDrawable horizonShadow;
    private TextView mTvListName;
    private LinearLayout mTvTitleBack;
    private LinearLayout mLlHelp;
    private View mMainTitle;//导航栏
    private LayoutInflater mLayoutInflater;
    private PopupWindow mOrderContactsWin;
    //键盘皮肤相关
    private ContactInfoActionButtonsLayout mMainLayout;
    private /*AmazingListView*/ PullListView mContactsListView;
    private int mKeyboardThemeColor = 0;
    public KeyboardVertFrag mKeyboardVertFrag;
    public KeyboardHoriFrag mKeyboardHoriFrag;
    public TreeFrag mTreeFrag;
    public CheckBox mCbSelectAll;

    private Bundle mBundle;
    private EventListData mEventData = null;
    public ElementData chooseelement;
    private HashMap<String, String> mUsers;
    public boolean mLongClickDial;
    private Handler mHandler;
    Messenger mMessenger;
    public int mFontSizeValue = 18;
    public boolean mShowTimesContacted;
    private String mUid;
    public ArrayList<CloudContact> rootcontactList;
    public int mKeyboardOri = 0;//键盘方向
    private int mIsHaveTone;//是否有声音
    static public SkinVertyData mVertySkin;//竖键盘数据
    static public SkinVertyData mVertySkin2;//竖键盘数据
    public SkinHorizData mHorizSkin;//横键盘数据
    public SkinCommonData mSkinCommon;//公共数据
    public String mInputTextT9;
    public String mInputTextQwerty;
    public static boolean isShowChange = false;
    public static boolean isSingleChoose; // true：单选   false：多选
    //键盘声音
    public Mp3Player player;
    private String mAction;
    public long mShareContactId;
    public static final String DATA = "DATA";
    private boolean mIsDisplayUnderPanel = true;
    public static boolean mIsLoad = true;
    public String mShareName;
    public String mSharePhone;
    public TextWatcher mTextWatcher = null;
    public TextWatcher mTextWatcherQwerty = null;
    private CloudDBOperation mCloudDBOperation;

    public ListStatus mListStatus;
    private static final int MSG_GET_NAMECARD = 1789;
    public static final int CLOUD_SEARCH_MSG = 200;
    public static final boolean STARTUP_TRACE = false;
    public boolean mIfBatchOperation = false;
    public boolean mIfShowPeopleNoPhone = true;
    private boolean mFirstQuery = true;
    private BackgroundQueryHandler mBackgroundQueryHandler;
    public static int mBatchOperationType = 0;
    public boolean isTextLoad = false;
    private boolean mIsAddGroupMember;
    private String mMemberCount; // 聊天小组的人数

    public static final int MSG_CONTACT_GETLIST = 3000;
    private static final int MSG_GROUP_CONTACT = 3001;
    private static final int MSG_CONTACT_ADDLIST = 3002;
    private static final int MSG_CONTACT_APPEND_LIST = 3003;
    private static final int MSG_SET_CONTACT = 3006;
    private static final int MSG_GROUP_MANAGER = 3007;
    private static final int MSG_GROUP_DELETE_MEMBER = 3008;
    private static final int MSG_ADD_RECEIVER_TO_EVENT = 3009;
    private static final int MSG_SCHEDULE_ADD_MANAGER = 3011;
    private static final int MSG_WEEKLY_ADD_MANAGER = 3012;

    public static final int MSG_CONTACT_UPDATE_LIST = 3013; // 刷新列表

    protected ImageLoader imageLoader = ImageLoader.getInstance();
    private ArrayList<CloudContact> mContactList = new ArrayList<CloudContact>();

    private AttendanceData attendanceData;
    /**
     * 联系人＊＊＊＊＊＊＊＊＊添加内容＊＊＊＊＊＊＊＊＊＊
     */
    private ArrayList<Long> mAllContactId = new ArrayList<Long>();
    private ArrayList<Long> mSelectedListContactId;
    public int mSortByProperty = 0;
    public CloudContactAdapter mCloudContactAdapter;
    private ContactEntryAdapter mContactEntryAdapter;
    private float mListDownY;
    public boolean whileLock = false;
    int contactedPeople = 0;
    private ResultListManager mListManager = null;
    private int mShowContent;
    public PinyinSearch mPinyinSearch;
    private HashMap<Long, String> mCloudUser = new HashMap<Long, String>();
    String chatGroupId;
    boolean isSingle;
    String userType;
    String eventId;
    String eventTypeId;
    String eventReceiver;

    public String tagId = "0";
    public String tagName = "";
    public String tagCount = "";
    public String groupId = "";
    public String groupName = "";
    public String tagPath = "";
    public String groupImg = "";
    public int groupType;
    public String contactId = "";
    public int contactCount;
    public ArrayList<Integer> clickPosition;
    public int currentPosition;
    public ArrayList<ChatContact> chatContacts;
    public int mCurrentPage = 0;
    public long mCloudGid;
    public CloudGroup mCloudGroup;
    public static CloudGroup selectedGroup = null;
    private boolean mLoading = false;

    public Handler mCloudHandler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            switch (msg.what) {
                case MSG_GET_NAMECARD:
                    if (msg.arg1 == 0) {

                        UpLoadContactsTask upload = new UpLoadContactsTask(mContext);
                        upload.execute();
                    } else if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                        String error = getString(R.string.active_failure_no_network);
                        Toast.makeText(mContext, error, Toast.LENGTH_SHORT).show();
                    } else if (msg.obj != null) {
                        Toast.makeText(CloudDialerActivity.this, (String) msg.obj,
                                Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(mContext, R.string.network_server_error,
                                Toast.LENGTH_LONG).show();
                    }
                    break;
                case MSG_CONTACT_UPDATE_LIST: // 刷新列表
                    if (msg.arg1 == 1) {
                        mContactList = (ArrayList<CloudContact>) msg.obj;
                        mContactsListView.onRefreshComplete("最近更新：" + DateUtil.getUpDateTime(System.currentTimeMillis()));
                        if (CloudDialerActivity.this.mTreeFrag != null) {
                            ArrayList<ChatContact> list = new ArrayList<ChatContact>();
                            for (int i = 0; i < mContactList.size(); i++) {
                                CloudContact cloud = mContactList.get(i);
                                ChatContact contact = new ChatContact(cloud.userId, cloud.contactName, cloud.contactId, cloud.contact_image);
                                list.add(contact);
                            }
                            CloudDialerActivity.this.mTreeFrag.setContactNum(list);
                        }
                        updateCloudContactList(mContactList);
                    }
                    break;
                case MSG_CONTACT_GETLIST:
                    if (msg.arg1 == 0 || msg.arg1 == 1) {
                        mContactList = (ArrayList<CloudContact>) msg.obj;
                        if (mIfBatchOperation) {
                            mShowModleChiceView.backToDefaultState();
//                            if (mCloudContactAdapter.mIsShowSelected) {
                            mCloudContactAdapter.changeToAllContent();
//                            }
                        }
                        updateCloudContactList(mContactList);
                        // 不是批处理 + 所有人员 才去保存数据库
                        if (msg.arg1 == 1 && mContactList.size() > 0 && mBatchOperationType == 0) {
                            new AsyncTask<Void, Void, Void>() {
                                @Override
                                protected Void doInBackground(Void... params) {
                                    long start = System.currentTimeMillis();
                                    for (int i = 0; i < mContactList.size(); i++) {
                                        CloudContact cloudContact = mContactList.get(i);
                                        if (cloudContact.contactPhoneNum != null && cloudContact.contactPhoneNum.size() != 0) {
                                            String phone = cloudContact.contactPhoneNum.get(0).phoneNum;
                                            List<String> contact = mCloudDBOperation.findOneContact(mUid, phone, cloudContact.groupId);
                                            if (contact.size() == 0) {
                                                mCloudDBOperation.insertContact(mUid, phone, cloudContact.contactWork, groupName, cloudContact.contactName, cloudContact.groupId);
                                            } else {
                                                // 如果名称换了，更新数据库
                                                if (!contact.get(0).equals(groupName) || !contact.get(2).equals(cloudContact.contactWork)) {
                                                    mCloudDBOperation.updateContact(mUid, phone, cloudContact.contactWork, groupName, cloudContact.contactName, cloudContact.groupId);
                                                }
                                            }
                                        }
                                    }
                                    Log.d("GetGroupListMsg:contact", "耗时:" + (System.currentTimeMillis() - start));
                                    return null;
                                }
                            }.execute();
                        }


                        //号码薄本地搜索
                        //////////////////////////////////////////////////////////////
                        /*
                        PinyinSearch.getInstance(null).clearGroupPinyinDict(gid);
                        for( CloudContact contact : contactList)
                        {
                        	PinyinSearch.getInstance(null).addGroupPinyinDict(contact.groupId, contact.contactName, Integer.valueOf(contact.contactId), (contact.contact_phone!=null && contact.contact_phone.length()>0) ? true : false );
                        }
                        */
                        //////////////////////////////////////////////////////////////


                    } else if (msg.arg1 == 1002 || msg.arg1 == 1003) {

                        mDialogUtil.titleMsgBtnStyle("提示", (String) msg.obj, mContext.getString(R.string.ok));
                        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

                            @Override
                            public void onConfirmClick(Dialog lDialog) {

                                lDialog.dismiss();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                                finish();


                            }

                            @Override
                            public void onCancelClick(Dialog lDialog) {
                            }
                        });
                    } else {
                        Toast.makeText(CloudDialerActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case MSG_CONTACT_APPEND_LIST:
                    //mContactsListView.onLoadComplete();
                    if (mListStatus != ListStatus.ENUM_SHOW_CLOUD_CONTACT) {
                        return;
                    }
                    mShowModleChiceView.backToDefaultState();
                    if (mIfBatchOperation && mCloudContactAdapter.mIsShowSelected) {
                        mCloudContactAdapter.changeToAllContent();
                    }
                    ArrayList<CloudContact> contactList = (ArrayList<CloudContact>) msg.obj;
                    if (msg.arg1 == 0) {
                        if (contactList.size() > 0) {
                            mCurrentPage++;
                        }
                        appendCloudContactList(contactList);
                    }
                    mLoading = false;
                    break;
                case MSG_CONTACT_ADDLIST:
                    if (msg.arg1 == 0) {

                        Map<String, String> object = (Map<String, String>) msg.obj;

                        String success_num = null;
                        String err_num = null;
                        String err_name = null;
                        String msgNote = "";
                        try {

                            success_num = (String) object.get("success_num");
                            err_num = (String) object.get("err_num");
                            err_name = (String) object.get("err_contact_names");

                            if ("0".equals(err_num)) {
                                msgNote = "成功导入" + success_num + "人,失败" + err_num + "人";
                            } else {
                                msgNote = "成功导入" + success_num + "人,失败" + err_num + "人,失败的人是:" + err_name;
                            }

                            if ("create_group_import_contact".equals(mAction) == false) {


                                mDialogUtil.titleMsgBtnStyle("提示", msgNote, getString(R.string.ok));
                                mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

                                    @Override
                                    public void onConfirmClick(Dialog lDialog) {
                                        lDialog.dismiss();
                                    }

                                    @Override
                                    public void onCancelClick(Dialog lDialog) {
                                    }
                                });

                            }

                            if (mTreeFrag != null) {
                                mTreeFrag.addContactNum(Integer.valueOf(success_num));
                            }

                        } catch (Exception e) {

                        }
                        if (showDepartment == false) {
                            CloudDialerActivity.this.ivChange.setBackgroundResource(R.drawable.key_turn_selector);
                        } else {
                            CloudDialerActivity.this.ivChange.setBackgroundResource(R.drawable.key_search_selector);
                        }

                        mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;
                        //mBatchOperitonTitle.setCompoundDrawables(null, null, null, null);
                        //freshContactsByStatus();
                        //batchOperation(Constants.BATCH_OPERATION_CLOUD_UPLOAD);
                        //mIsCreate = false;
                        if (changebundle != null) {
                            mCloudGid = Long.parseLong(changebundle.getString("group_id"));
                            groupId = changebundle.getString("group_id");
                            groupName = changebundle.getString("group_name");
                            try {
                                contactCount = Integer.parseInt(changebundle.getString("contact_count"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else if ("cloud_contact_list".equals(mAction)) {
                            quitBatchOperation(true, true);
                            getCloudContactList(String.valueOf(mCloudGid), 0, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
                            return;

                        } else if ("create_group_import_contact".equals(mAction)) {
                            Intent backintent = new Intent();
                            Bundle bundle = new Bundle();
                            bundle.putString("msgNote", msgNote);
                            backintent.putExtras(bundle);
                            setResult(0, backintent);
                            finish();
                            return;

                        } else {
                            finish();
                            return;
                        }
                        Intent intent = new Intent();
                        intent.putExtra(Constants.INTENT_TAG_ID, "-1");
                        intent.putExtra(Constants.INTENT_TAG_NAME, "全部成员");
                        intent.putExtra("group_id", groupId);
                        intent.putExtra("group_name", groupName);
                        intent.putExtra("contact_count", String.valueOf(contactCount));
                        intent.putExtra("contact_id", contactId);
                        intent.setAction("structure_tag_click");
                        CloudDialerActivity.instance.ListRefresh(intent, Activity.RESULT_OK, null);
                        keyBoardVert(true, null, showDepartment);

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(CloudDialerActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            mDialogUtil.titleMsgBtnStyle("提示", (String) msg.obj, getString(R.string.ok));
                            mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

                                @Override
                                public void onConfirmClick(Dialog lDialog) {
                                    lDialog.dismiss();
                                    finish();
                                }

                                @Override
                                public void onCancelClick(Dialog lDialog) {
                                }
                            });
                        }
                    }
                    break;
                case MSG_GROUP_CONTACT:
                    if (msg.arg1 == 0) {
                        @SuppressWarnings("unchecked")
                        ArrayList<CloudContact> contactList2 = (ArrayList<CloudContact>) msg.obj;
                        if (contactList2 != null) {
                            Log.i("size", contactList2.size() + "");
                        }
                        updateCloudContactList(contactList2);
                    }
                    break;
                case MSG_SET_CONTACT:
                    if (msg.arg1 == 0) {
                        if (mDialog != null) {
                            mDialog.dismiss();
                        }
                        mIsAddGroupMember = false;

                        mBatchOperationType = 0;
                        if (mBatchOperationType == 0) {


                            if (CloudDialerActivity.this.mTreeFrag != null) {
                                CloudDialerActivity.this.mTreeFrag.setContactNum(CloudDialerActivity.this.mCloudContactAdapter.getSelectedContacts());

                            }


                            quitBatchOperation(true, true);
                            freshContactsByStatus();
                            if (mCloudContactAdapter != null) {
                                mCloudContactAdapter.clearSelected();
                                mCloudContactAdapter.setIfCheckBoxShow(false);
                            }
                        }
                        //finish();
                        showDepartment = true;

                        if (showDepartment == false) {
                            CloudDialerActivity.this.ivChange.setBackgroundResource(R.drawable.key_turn_selector);
                        } else {
                            CloudDialerActivity.this.ivChange.setBackgroundResource(R.drawable.key_search_selector);
                        }

                        mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;
                        //mBatchOperitonTitle.setCompoundDrawables(null, null, null, null);
                        //freshContactsByStatus();
                        //batchOperation(Constants.BATCH_OPERATION_CLOUD_UPLOAD);
                        //mIsCreate = false;



                    /*
                        Intent intent = new Intent();
                        intent.putExtra(Constants.INTENT_TAG_ID, "0");
                        intent.putExtra(Constants.INTENT_TAG_NAME, "全部成员");
                        intent.putExtra("tag_count", "");
                        intent.putExtra("group_id", groupId);
                        intent.putExtra("group_name", groupName);
                        //intent.putExtra("contact_count", changebundle.getString("contact_count"));


                        intent.setAction("structure_tag_click");
                    */
                        CloudDialerActivity.instance.initIntentData();//initIntentData(intent);

                        mTreeFrag.clearContactList();
                        keyBoardVert(true, null, showDepartment);


                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(CloudDialerActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(CloudDialerActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case MSG_GROUP_MANAGER:
                    if (msg.arg1 == 0) {
                        finish();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(CloudDialerActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(CloudDialerActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case MSG_GROUP_DELETE_MEMBER:
                    if (msg.arg1 == 0) {
                        Intent intent = new Intent(CloudDialerActivity.this, ManageGroupActivity.class);
                        /*intent.putExtra("group_name", groupName);
                        intent.putExtra("group_id", groupId);
                        intent.putExtra("contact_id", contactId);
                        intent.putExtra("create_type", userType);*/
                        if (mCloudGroup != null) {
                            intent.putExtra("groupData", mCloudGroup);
                        }
                        intent.putExtra("where", "delete_member");
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        Toast.makeText(mContext, "删除成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(mContext, "删除失败", Toast.LENGTH_SHORT).show();
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(CloudDialerActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(CloudDialerActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case MSG_ADD_RECEIVER_TO_EVENT:
                    if (msg.arg1 == 0) {
                        Intent intent = new Intent(CloudDialerActivity.this, EventReceiveMemberActivity.class);
                        intent.putExtra("event_id", eventId);
                        intent.putExtra("event_type", eventTypeId);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                    break;
                case MSG_SCHEDULE_ADD_MANAGER:
                    if (msg.arg1 == 0) {
                        Intent intent = new Intent(CloudDialerActivity.this, ScheduleManagerActivity.class);
                        intent.setAction(msg.obj.toString());
                        /*if (mCloudGroup != null) {
                            intent.putExtra("groupData", mCloudGroup);
                        }*/
                        intent.putExtra("groupData",selectedGroup);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(CloudDialerActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(CloudDialerActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case MSG_WEEKLY_ADD_MANAGER:
                    if (msg.arg1 == 0) {
                        Intent intent = new Intent(CloudDialerActivity.this, ScheduleManagerActivity.class);
                        intent.setAction(msg.obj.toString());
                        intent.putExtra("group_data",selectedGroup);
//                        intent.putExtra("groupId", groupId);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(CloudDialerActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(CloudDialerActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CloudDialerActivity.instance = this;

        setContentView(R.layout.cloud_dialer_list);
        mContext = this;
        mDialogUtil = AllDialogUtil.getInstance(this);
        initProperty();
        initView(getIntent());
        initRootViewInKeyboard();
        initSkin();
        initTextWatcher();
        setSelectImage(false);
        SealAppContext.getInstance().pushActivity(this);

        mHandler = new BackgroundHandler();
        mMessenger = new Messenger(mHandler);
        updateKeypadVisibility(null);

        mLayoutInflater = getLayoutInflater();
        mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
        initListStatus(getIntent());
        initListManager(getIntent());
        setComponet(mSkinCommon);
//      setupShakeListener();
        /*
        int key = mPreferenceUtil.getInt(PreferenceUtil.CONTACT_KEYBOARD_LAYOUTORIENTATION, 1);
        setKeyBoardOrientation(key);
        */
        mIsLoad = true;

        setFilterText("");
        if (mPinyinSearch == null) {
            mPinyinSearch = PinyinSearch.getInstance(this.getApplicationContext());
        }

        Intent intent = getIntent();
        //chooseelement = new Element();
        String groupId = intent.getStringExtra("group_id");
        gid = groupId;
        groupName = intent.getStringExtra("group_name");

        if (mListStatus == ListStatus.ENUM_SHOW_CLOUD_CONTACT) {
            if (selectedGroup == null && !StringUtil.isEmpty(gid) && !"null".equals(gid)){
                selectedGroup = new CloudGroup();
                selectedGroup.groupId = Long.parseLong(gid);
                selectedGroup.groupName = StringUtil.isEmpty(groupName) ? "企业":groupName;
                selectedGroup.contactCount = 10;
                Log.d("my_selectedGroup","  ==1==  " + selectedGroup.toString());
            }
            if (selectedGroup == null && !StringUtil.isEmpty(gid) && !"null".equals(gid)){
                CloudDBOperation mCloudDBOperation = new CloudDBOperation(CloudDialerActivity.this);
                selectedGroup = mCloudDBOperation.getOneLocalGroupList(gid);
                Log.d("my_selectedGroup","  ==2==  " + selectedGroup.toString());
            }
            updateCloudContactList(null);
        } else {
            //freshContactsByStatus();
            mBatchOperitonTitle.setText("本地通讯录");
            mTvListName.setText("本地通讯录");
            this.llChange.setVisibility(View.GONE);
        }

        // TODO 默认搜索框内没有搜索字


 /*
        if (mBatchOperationType == 0) {
            quitBatchOperation(true, true);
            freshContactsByStatus();

            if (mCloudContactAdapter != null) {
                mCloudContactAdapter.clearSelected();
                mCloudContactAdapter.setIfCheckBoxShow(false);
            }

        }
  */
        /*
        if (!StringUtil.isEmpty(groupId)) {
            chooseelement.groupId = Integer.valueOf(groupId);
        }
		*/

        if (mIsLoad) {
            initIntentData();
        }

        mContactsListView.setType(1);
        mContactsListView.setonRefreshListener(new PullListView.OnRefreshListener() {
            @Override
            public void onRefresh(boolean isTop) {
                if (mListStatus == ENUM_SHOW_CLOUD_CONTACT && mBatchOperationType == 0) {
                    getCloudContactList(String.valueOf(mCloudGid), mCurrentPage,
                            mCloudHandler.obtainMessage(MSG_CONTACT_UPDATE_LIST), tagId, contactId);
                } else {
                    mContactsListView.onRefreshComplete("最近更新：" + DateUtil.getUpDateTime(System.currentTimeMillis()));
                }
            }
        });

    }

    String gid;

    @Override
    protected void onStart() {
        super.onStart();
        if (mPinyinSearch == null) {
            mPinyinSearch = PinyinSearch.getInstance(this.getApplicationContext());
        }
    }


    public void initProperty() {
        mCloudDBOperation = new CloudDBOperation(mContext);
        mPreferenceUtil = PreferenceUtil.getInstance(mContext);
        mLongClickDial = mPreferenceUtil.getPreference().getBoolean(PreferenceUtil.LONG_CLICK_DIAL, true);
        mKeyboardThemeColor = mPreferenceUtil.get(PreferenceUtil.CONTACT_KEYBOARD_THEMECOLOR,
                Integer.class);    // 0
        mSortByProperty = mPreferenceUtil.getInt(PreferenceUtil.CONTACT_NAME_SORT,
                Constants.ORDER_BY_CALL_LOG_INDEX);
        mShowTimesContacted = mPreferenceUtil.getBoolean(PreferenceUtil.SHOW_TIMES_CONTACTED, true);

        Boolean flag = mPreferenceUtil
                .get(PreferenceUtil.SHOW_PEOPLE_NO_PHONENUMBER, Boolean.class);
        if (flag != null) {
            mIfShowPeopleNoPhone = flag;
        }
        mDialog = new Dialog(mContext, android.R.style.Theme_Translucent_NoTitleBar);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDialog.setContentView(R.layout.wait_layout);
        mUid = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");
    }

    LinearLayout llChange;
    ImageView ivChange;

    /**
     * 初始化页面元素
     */
    private void initView(Intent intent) {
        mKeyBoardMainContainer = (LinearLayout) findViewById(R.id.keybord_container);
        mMainLayout = (ContactInfoActionButtonsLayout) findViewById(R.id.mainLayout);
        mTvTitleBack = (LinearLayout) findViewById(R.id.tv_back);
        mTvTitleBack.setOnClickListener(this);
        mLlHelp = (LinearLayout) findViewById(R.id.keyboard_title_ll_help);
        mLlHelp.setOnClickListener(this);
        llChange = (LinearLayout) findViewById(R.id.ll_change);
        ivChange = (ImageView) findViewById(R.id.iv_change);
        llChange.setOnClickListener(this);
        //this.ivChange.setBackgroundResource(R.drawable.btn_department_search);

        mContactsListView = (/*AmazingListView*/PullListView) findViewById(R.id.contactslist);
        mTvListName = (TextView) findViewById(R.id.tv_group_name);
        //mTvListName.setOnClickListener(this);
        /*
        mContactsListView.setonRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                mContactsListView.onRefreshComplete();
                orderContactsWindow();
            }
        });
        */
        //加载更多
//        mContactsListView.setOnLoadListener(new AmazingListView.OnLoadListener() {
//            @Override
//            public void onLoad() {
//                appendCloudContactListReq();
//            }
//        });

        mTitleBarSelectMode = (RelativeLayout) findViewById(R.id.title_bar_select_mode);
        mTitleBarNormalMode = (RelativeLayout) findViewById(R.id.title_bar_normal_mode);
        //isShowChange=true;
        mBtnCancel = (/*LinearLayout*/TextView) mTitleBarSelectMode.findViewById(R.id.mainactvity_cancel);
        mBtnCancel.setOnClickListener(this);
        mBtnSend = (TextView) mTitleBarSelectMode.findViewById(R.id.mainactivity_btn_send);
        mBtnSend.setOnClickListener(this);
        mBatchOperitonTitle = (TextView) mTitleBarSelectMode.findViewById(R.id.mainactivity_tv_title);
        //mBatchOperitonTitle.setOnClickListener(this);
        mTabSelectAll = (LinearLayout) findViewById(R.id.select_all);
        mLayoutSelectAll = (LinearLayout) findViewById(R.id.select_all_layout);
        mTabSelectAll.setOnClickListener(this);
        mCbSelectAll = (CheckBox) findViewById(R.id.cb_slect_all);
        mShowModleChiceView = (TwiceTextChoiceView) findViewById(R.id.ttc_select);
        mShowModleChiceView.setOnChoiceChangeListener(new MyOnChoiceChangeListener());
        mBatchOpertionLayout = (LinearLayout) findViewById(R.id.ll_batck_opertion);
        mMainTitle = findViewById(R.id.main_title);
        //mVerticalPadScrollView = (VerticalKeyPadScrollLayout) findViewById(R.id.vertical_scroll_layout);
        mNull = (TextView) findViewById(R.id.tv_null);


        if ("local_contact_list".equals(intent.getAction())) {//正常进入本地联系人列表

            CloudDialerActivity.isShowChange = false;
        } else if ("cloud_contact_list".equals(intent.getAction())) {//正常进入云端联系人列表
            CloudDialerActivity.isShowChange = false;
        } else {
            CloudDialerActivity.isShowChange = true;
        }
        mHelpSlipKey = (ImageView) findViewById(R.id.slip_key);
        mHelpStructureAdd = (ImageView) findViewById(R.id.structure_add);
        mHelpStructureEdit = (ImageView) findViewById(R.id.structure_edit);
        mHelpSlipKey.setOnClickListener(this);
        mHelpStructureAdd.setOnClickListener(this);
        mHelpStructureEdit.setOnClickListener(this);

        boolean isFirst = mPreferenceUtil.getBoolean("slip_key_v1", true);
        if (isFirst) {
            mHelpSlipKey.setVisibility(View.VISIBLE);
        } else {
            mHelpSlipKey.setVisibility(View.GONE);
        }

    }


    public void initIntentData(Intent intent) {
        if (mKeyboardVertFrag != null) {
            mKeyboardVertFrag.enableInput(true);
        }
        String mAction = intent.getAction();
        if ("set_structure_group_contact".equals(mAction)) {//组织结构设置部门成员
            showDepartment = false;
            usechange = false;

            if (showDepartment == false) {
                this.ivChange.setBackgroundResource(R.drawable.key_turn_selector);
            } else {
                this.ivChange.setBackgroundResource(R.drawable.key_search_selector);
            }

            keyBoardVert(true, null, showDepartment);


            mBatchOperitonTitle.setCompoundDrawables(null, null, null, null);
            mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;
//            isRefreshable();
            //mContactsListView.setCanRefreshable(false);
            //updateCloudContactList(null);
            Bundle bundle = intent.getExtras();
            contactId = bundle.getString("contact_id");
            tagId = bundle.getString("tag_id");
            tagName = bundle.getString(Constants.INTENT_TAG_NAME);
            tagCount = "";
            groupId = bundle.getString("group_id");
            mCloudGid = Long.parseLong(intent.getStringExtra("group_id"));
            tagPath = bundle.getString("tag_path");
            groupName = bundle.getString("group_name");
//                    chatContacts = (ArrayList<ChatContact>) bundle.getSerializable("select");
            clickPosition = bundle.getIntegerArrayList("clickPosition");
            currentPosition = bundle.getInt("currentPosition");
            contactCount = intent.getIntExtra("contact_count", 0);
            chatContacts = intent.getParcelableArrayListExtra("selectedContact");
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);
            batchOperation(Constants.BATCH_OPERATION_ADD_GROUP_MEMBER);
        } else if ("structure_add_local_member".equals(mAction)) {//组织结构添加本地联系人
            mListStatus = ListStatus.ENUM_SHOW_CONTACT_INFO;
            setNoData(false);
            setSelectImage(false);
            showDepartment = false;
            if (showDepartment == false) {
                this.ivChange.setBackgroundResource(R.drawable.key_turn_selector);
            } else {
                this.ivChange.setBackgroundResource(R.drawable.key_search_selector);
            }

            keyBoardVert(true, null, showDepartment);
            mBatchOperitonTitle.setCompoundDrawables(null, null, null, null);
            batchOperation(Constants.BATCH_OPERATION_CLOUD_UPLOAD);
            freshContactsByStatus();

            //mCloudGid = Long.parseLong(intent.getStringExtra("group_id"));
            //groupId = intent.getStringExtra("group_id");
            //groupName = intent.getStringExtra("group_name");
            //contactCount = intent.getIntExtra("contact_count", 0);
            contactId = intent.getStringExtra("contact_id");
        }
    }


    private void initIntentData() {
        Intent intent = getIntent();

        if (!"structure_tag_click".equals(mAction)) {
            mAction = intent.getAction();
        }
        if ("local_contact_list".equals(mAction)) {//正常进入本地联系人列表

            mListStatus = ListStatus.ENUM_SHOW_CONTACT_INFO;
            freshContactsByStatus();
            mTvListName.setCompoundDrawables(null, null, null, null);
        } else if ("cloud_contact_list".equals(mAction)) {//正常进入云端联系人列表
            if (mListManager == null) {
                mListManager = new ResultListManager(this, mContactsListView, mShowContent);
            }


            mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;

//          isRefreshable();
            //mContactsListView.setCanRefreshable(false);
            //updateCloudContactList(null);
            groupId = intent.getStringExtra("group_id");
            mCloudGid = Integer.parseInt(intent.getStringExtra("group_id"));
            tagId = intent.getStringExtra("tag_id");
            tagName = intent.getStringExtra("tag_name");
            groupName = intent.getStringExtra("group_name");
            contactId = intent.getStringExtra("contact_id");
            groupImg = intent.getStringExtra("group_img");
            groupType = intent.getIntExtra("group_type", 0);
            Log.i("group_type", " cloud get " + groupType);
            userType = intent.getStringExtra("user_type");
            mPreferenceUtil.save("create_type", userType);
            contactCount = intent.getIntExtra("contact_count", 0);
            if (mCloudContactAdapter != null && contactId != null)
                mCloudContactAdapter.setCurrentContactId(contactId);
            if (!tagId.equals("-1")) {
                getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
            } else {
                getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);
            }
        } else if ("share_contact".equals(mAction)) {//我页面分享联系人名片
            mShareName = intent.getStringExtra(Constants.CONTACT_NAME_KEY);
            mSharePhone = intent.getStringExtra(Constants.CONTACT_PHONE_KEY);
            mShareContactId = intent.getLongExtra(Constants.CONTACT_ID_KEY, -1L);
            mListStatus = ListStatus.ENUM_SHOW_CONTACT_INFO;
            freshContactsByStatus();
            batchOperation(Constants.CHECKBOX_STATUS_BUSINESSCARD_WITHSMS);
        } else if ("create_group_import_contact".equals(mAction)) {//创建号码簿时导入联系人
            long groudId = intent.getLongExtra("group_id", -1);
            selectedGroup = (CloudGroup) intent.getSerializableExtra(CloudGroup.class.getName());
            addContactToGroupDirect(groudId);
        } else if ("contact_detail_page_share".equals(mAction)) {
            mShareName = intent.getStringExtra(Constants.CONTACT_NAME_KEY);
            mSharePhone = intent.getStringExtra(Constants.CONTACT_PHONE_KEY);
            mShareContactId = intent.getLongExtra(Constants.CONTACT_ID_KEY, -1L);
            mListStatus = ListStatus.ENUM_SHOW_CONTACT_INFO;
            freshContactsByStatus();
            batchOperation(Constants.CHECKBOX_STATUS_BUSINESSCARD_WITHSMS);
        } else if ("manage_add_manager".equals(mAction)) {
            if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_MANAGER_ADD) != 0) {

            } else {
                tagId = intent.getStringExtra(Constants.INTENT_TAG_ID);
                tagName = intent.getStringExtra(Constants.INTENT_TAG_NAME);
                tagCount = intent.getStringExtra("tag_count");
                groupId = intent.getStringExtra("group_id");
                mCloudGid = Long.parseLong(intent.getStringExtra("group_id"));
                groupName = intent.getStringExtra("group_name");
                contactCount = intent.getIntExtra("contact_count", 0);
                contactId = intent.getStringExtra("contact_id");
                userType = intent.getStringExtra("create_type");
                //updateCloudContactList(null);
                if (!"-1".equals(tagId)) {
                    getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
                } else {
                    getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);
                }
                batchOperation(Constants.BATCH_OPERATION_MANAGER_ADD);
            }
        } else if ("manage_delete_member".equals(mAction)) {
            if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_MEMBER_DELETE) != 0) {

            } else {
               /* tagId = intent.getStringExtra(Constants.INTENT_TAG_ID);
                tagName = intent.getStringExtra(Constants.INTENT_TAG_NAME);
                tagCount = intent.getStringExtra("tag_count");
                groupId = intent.getStringExtra("group_id");
                mCloudGid = Long.parseLong(intent.getStringExtra("group_id"));
                groupName = intent.getStringExtra("group_name");
                contactCount = intent.getIntExtra("contact_count", 0);
                contactId = intent.getStringExtra("contact_id");
                userType = intent.getStringExtra("create_type");*/
                mCloudGroup = (CloudGroup) intent.getSerializableExtra("groupData");
                groupId = mCloudGroup.groupId + "";
                groupName = mCloudGroup.groupName;
                groupType = mCloudGroup.groupType;
                contactId = mCloudGroup.contactId;
                userType = mCloudGroup.userType;
                //updateCloudContactList(null);
                getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);
                batchOperation(Constants.BATCH_OPERATION_MEMBER_DELETE);
            }
        } else if ("events_add_receiver".equals(mAction)) {
            mBundle = intent.getBundleExtra("event_msg");
            mEventData = (EventListData) mBundle.getSerializable("event_bundle");
            eventReceiver = mEventData.getReceiver();

            if ("local".equals(mBundle.getString("where"))) {
                mListStatus = ListStatus.ENUM_SHOW_CONTACT_INFO;
                freshContactsByStatus();
                batchOperation(Constants.BATCH_OPERATION_EVENT_ADD_LOCAL_RECEIVER);
                mBatchOperitonTitle.setCompoundDrawables(null, null, null, null);
            } else {
                mListStatus = CloudDialerActivity.ListStatus.ENUM_SHOW_CLOUD_CONTACT;
                //updateCloudContactList(null);
                tagId = intent.getStringExtra("tag_id");
                tagName = intent.getStringExtra("tag_name");
                tagCount = intent.getStringExtra("tag_count");
                groupId = intent.getStringExtra("group_id");
                mCloudGid = Long.parseLong(intent.getStringExtra("group_id"));
                groupName = intent.getStringExtra("group_name");
                contactCount = intent.getIntExtra("contact_count", 0);
                contactId = intent.getStringExtra("contact_id");
                userType = intent.getStringExtra("user_type");
                getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
                batchOperation(Constants.BATCH_OPERATION_EVENT_ADD_RECEIVER);
            }
        } else if ("create_chat_group".equals(mAction)) {
            chatGroupId = intent.getStringExtra("chat_group_id");
            chatContacts = (ArrayList<ChatContact>) intent.getSerializableExtra("member");
            isSingle = intent.getBooleanExtra("isSingle", true);
            userType = intent.getStringExtra("user_type");
            if ("local".equals(intent.getStringExtra("where"))) {
                mListStatus = ListStatus.ENUM_SHOW_CONTACT_INFO;
                freshContactsByStatus();
                batchOperation(Constants.BATCH_OPERATION_ADD_LOCAL_CHAT_MEMBER);
                mBatchOperitonTitle.setCompoundDrawables(null, null, null, null);
            } else {
                mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;
                //updateCloudContactList(null);
                tagId = intent.getStringExtra("tag_id");
                tagName = intent.getStringExtra("tag_name");
                tagCount = intent.getStringExtra("tag_count");
                groupId = intent.getStringExtra("group_id");
                mCloudGid = Long.parseLong(intent.getStringExtra("group_id"));
                groupName = intent.getStringExtra("group_name");
                contactCount = intent.getIntExtra("contact_count", 0);
                contactId = intent.getStringExtra("contact_id");
                userType = intent.getStringExtra("user_type");
                getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
                batchOperation(Constants.BATCH_OPERATION_ADD_CLOUD_CHAT_MEMBER);
            }
        } else if ("event_add_receiver".equals(mAction)) {
            eventId = intent.getStringExtra("event_id");
            eventTypeId = intent.getStringExtra("event_type");
            if ("local".equals(intent.getStringExtra("where"))) {
                mListStatus = ListStatus.ENUM_SHOW_CONTACT_INFO;
                freshContactsByStatus();
                batchOperation(Constants.BATCH_OPERATION_EVENT_ADD_LOCAL_RECEIVER);
                mBatchOperitonTitle.setCompoundDrawables(null, null, null, null);
            } else {
                mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;
                //updateCloudContactList(null);
                tagId = intent.getStringExtra("tag_id");
                tagName = intent.getStringExtra("tag_name");
                tagCount = intent.getStringExtra("tag_count");
                groupId = intent.getStringExtra("group_id");
                mCloudGid = Long.parseLong(intent.getStringExtra("group_id"));
                groupName = intent.getStringExtra("group_name");
                contactCount = intent.getIntExtra("contact_count", 0);
                contactId = intent.getStringExtra("contact_id");
                userType = intent.getStringExtra("user_type");
                getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
                batchOperation(Constants.BATCH_OPERATION_EVENT_ADD_RECEIVER);
            }
        } else if ("schedule_manager_add".equals(mAction)) {
            mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;
            //updateCloudContactList(null);
            tagId = intent.getStringExtra("tag_id");
            tagName = intent.getStringExtra("tag_name");
            tagCount = intent.getStringExtra("tag_count");
            groupId = intent.getStringExtra("group_id");
            mCloudGid = Long.parseLong(intent.getStringExtra("group_id"));
            groupName = intent.getStringExtra("group_name");
            contactCount = intent.getIntExtra("contact_count", 0);
            contactId = intent.getStringExtra("contact_id");
            userType = intent.getStringExtra("user_type");
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
            batchOperation(Constants.BATCH_OPERATION_SCHEDULE_MANAGER);

        } else if ("attendance_member_add".equals(mAction)) {
            mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;
            //updateCloudContactList(null);
            tagId = intent.getStringExtra("tag_id");
            tagName = intent.getStringExtra("tag_name");
            tagCount = intent.getStringExtra("tag_count");
            groupId = intent.getStringExtra("group_id");
            mCloudGid = Long.parseLong(intent.getStringExtra("group_id"));
            groupName = intent.getStringExtra("group_name");
            contactCount = intent.getIntExtra("contact_count", 0);
            contactId = intent.getStringExtra("contact_id");
            userType = intent.getStringExtra("user_type");
            attendanceData = (AttendanceData) intent.getSerializableExtra("attendanceData");
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
            batchOperation(Constants.BATCH_OPERATION_ATTENDANCE_MEMBER);
        } else if ("approval_leader_add".equals(mAction)) {
            mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;
            /*mPassGroup = (CloudGroup) intent.getSerializableExtra("groupData");
            groupName = mPassGroup.groupName;
            isSingleChoose = true;
            mLayoutSelectAll.setVisibility(View.GONE);
            mShowModleChiceView.setVisibility(View.GONE);*/
            tagId = intent.getStringExtra("tag_id");
            tagName = intent.getStringExtra("tag_name");
            tagCount = intent.getStringExtra("tag_count");
            groupId = intent.getStringExtra("group_id");
            mCloudGid = Long.parseLong(intent.getStringExtra("group_id"));
            groupName = intent.getStringExtra("group_name");
            contactCount = intent.getIntExtra("contact_count", 0);
            contactId = intent.getStringExtra("contact_id");
            userType = intent.getStringExtra("user_type");
            mCloudGroup = (CloudGroup) intent.getSerializableExtra("groupData");
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "0", contactId);
            batchOperation(Constants.BATCH_OPERATION_APPROVAL_LEADER);
        } else if ("weekly_manager_add".equals(mAction)) {
            mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;
//            tagId = intent.getStringExtra("tag_id");
//            tagName = intent.getStringExtra("tag_name");
//            tagCount = intent.getStringExtra("tag_count");
            groupId = intent.getStringExtra("group_id");
            if(!StringUtil.isEmpty(groupId)){
               mCloudGid = Long.parseLong(groupId);
            }
            groupName = intent.getStringExtra("group_name");
            contactCount = intent.getIntExtra("contact_count", 0);
            contactId = intent.getStringExtra("contact_id");
//            userType = intent.getStringExtra("user_type");
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "0", contactId);
            batchOperation(Constants.BATCH_OPERATION_WEEKLY_MANAGER);

        }
    }


    /**
     * 云端搜索无结果时，显示无结果
     *
     * @param flag true：显示   false ：不显示
     */

    public void setNoData(boolean flag) {
        if (flag) {
            mNull.setVisibility(View.VISIBLE);
        } else {
            mNull.setVisibility(View.GONE);
        }

    }


    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    }


    private String mText = "";

    /**
     * 初始化输入框edittext内容监听
     */
    private void initTextWatcher() {

        // T9搜索
        mTextWatcher = new TextWatcher() {
            public void afterTextChanged(final Editable aEditable) {
                mInputTextT9 = aEditable.toString();
                textChanged(aEditable, 1);
            }

            public void beforeTextChanged(final CharSequence aCharSequence, final int aStart,
                                          final int aCount, final int aAfter) {
            }

            public void onTextChanged(final CharSequence aCharSequence, final int aStart,
                                      final int aBefore, final int aCount) {
            }
        };

        // 字母搜索
        mTextWatcherQwerty = new TextWatcher() {
            public void afterTextChanged(final Editable aEditable) {
                mInputTextQwerty = aEditable.toString();
                Log.d("textChanged_search", "  mTextWatcherQwerty  ========  " + mInputTextT9);
                textChanged(aEditable, 1);
            }

            public void beforeTextChanged(final CharSequence aCharSequence, final int aStart,
                                          final int aCount, final int aAfter) {
            }

            public void onTextChanged(final CharSequence aCharSequence, final int aStart,
                                      final int aBefore, final int aCount) {
            }
        };
    }

    public static final int CLOUD_SEARCH_IDLE = 100;
    public static final int CLOUD_SEARCH_PENDING_SEND = 101;
    public static int sCloudSearch = CLOUD_SEARCH_IDLE;
    public static final int CLOUD_SEARCH_SEND_OUT = 102;


    private void textChanged(final Editable aEditable, int type) {
        if (type == 1) {
            if (aEditable == null) {
                mText = null;
            } else {
                // 防止T9键盘重复搜索
                String searchText = aEditable.toString();
                if (mText.equals(searchText)) {
                    return;
                }
                mText = aEditable.toString();
                mText = CloudGroupListCenter.searchReplace(mText);
                if (mText.length() > 20) {
                    return;
                }
                Log.d("textChanged_search", "  搜索  ========  " + mText);
            }
        }
        if (mListStatus == ListStatus.ENUM_SHOW_CLOUD_CONTACT) {
            sCloudSearch = CLOUD_SEARCH_PENDING_SEND;
            if (StringUtil.isEmpty(mText)) {
                mPinyinSearch.mContactIdPosition.clear();
                mCloudContactAdapter.setInterrupted(false);
                if (!StringUtil.isEmpty(contactId)) {
                    if (isTextLoad) {
                        if (rootcontactList == null) {
                            getCloudContactList(String.valueOf(mCloudGid), 0, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "0", contactId);
                        } else {
                            updateCloudContactList(rootcontactList);
                        }
                    }
                }
            } else {
                isTextLoad = true;
                mCloudContactAdapter.setInterrupted(true);
                sendPys(mText, mCloudGid, AsynHttpClient.DEFAULT_PAGE_SIZE, 0,
                        mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "0");
            }
            return;
        }
        /*
        Message message = mHandler.obtainMessage();
        message.what = Constants.UPDATE_AREA;
        message.obj = mText;
        mHandler.removeMessages(Constants.UPDATE_AREA);
        mHandler.sendMessage(message);
		*/
        if ((null == mText) || (0 == mText.length())) {
            // step2.1 if mDispyalCallLog is true, will return to call
            // log page
//            if (mDisplayCallLog) {
//                if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_SENDSMS) != 0
//                        || (mBatchOperationType & 1 << Constants.BATCH_OPERATION_SENDCARD) != 0
//                        || (mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADDGROUP) != 0
//                        || (mBatchOperationType & 1 << Constants.BATCH_OPERATION_RINGTONE) != 0
//                        // HEIHEI: why here need this?
//                        || checkboxSelectedFor(Constants.CHECKBOX_STATUS_BUSINESSCARD_WITHSMS)
//                        || checkboxSelectedFor(Constants.CHECKBOX_STATUS_BUSINESSCARD)
//                        || checkboxSelectedFor(Constants.CHECKBOX_STATUS_SELECT_BLACKLIST)
//                        || checkboxSelectedFor(Constants.CHECKBOX_STATUS_SELECT_WHITELIST)
//                        || checkboxSelectedFor(Constants.CHECKBOX_STATUS_SAVE2_OLD_CONTACT)) {
//                    freshContactsByStatus();
//                }
//            } else {
            freshContactsByStatus();
            //  }
            mContactEntryAdapter.setCurrentSearchText(null);
            mContactEntryAdapter.setInterrupted(false);
        } else {
            //            inputRemoveCursorVisible();
            mContactEntryAdapter.setInterrupted(true);
            mContactEntryAdapter.setCurrentSearchText(mText);
            if (mListManager != null) {
                mListManager.onRefresh(mText, mIfShowPeopleNoPhone);
            }
            //           isRefreshable();
            //mContactsListView.setCanRefreshable(false);
        }

    }


    /**
     * 向服务器请求云号码联系人列表
     *
     * @param key
     * @param gid
     * @param pageSize
     * @param pageIndex
     * @param callback
     * @param tagId
     */
    private void sendPys(String key, long gid, String pageSize, int pageIndex, Message callback, String tagId) {
        if (TextUtils.isEmpty(key)) {
            return;
        }

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        if (!StringUtil.isEmpty(tagId) && !mIsAddGroupMember) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TAG_ID, tagId));
        } else {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TAG_ID, "0"));
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CURRENT_CONTACT_ID, contactId));
        //        String geoHash = GetGeoHash.getInstance(this).getGeoHash();
        //        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GEO, geoHash));

        StringBuilder sb = new StringBuilder(AsynHttpClient.API_PYS);
        if (CloudGroupListCenter.isT9Key(key)) {
            sb.append("/t9");
        } else {
            sb.append("/zm");
        }
//        sb.append("/zm");
        sb.append('/').append(key).append('/').append(String.valueOf(gid)).append('/')
                .append(pageSize).append('/').append(String.valueOf(pageIndex));

        CloudSearchMsg cloudSearchMsg = new CloudSearchMsg(callback);
        cloudSearchMsg.type = CLOUD_SEARCH_MSG;
        cloudSearchMsg.mApi = sb.toString();
        cloudSearchMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execCcHttp(cloudSearchMsg);
    }

    public enum ListStatus {
        ENUM_SHOW_CONTACT_INFO, ENUM_SHOW_CLOUD_CONTACT
    }

    boolean showDepartment = false;

    /**
     * 处理横竖键盘的显示隐藏逻辑
     *
     * @param input
     */
    private void updateKeypadVisibility(String input) {
        if (mKeyboardOri == Constants.KEYBOARD_LAYOUT_VERTICAL) {
            //keyBoardHori(false, input);
            keyBoardVert(true, input, showDepartment);

            updateShadow(Constants.KEYBOARD_LAYOUT_VERTICAL, mKeypadAtRight);
            if (!mKeypadAtRight) {
                View v = mMainLayout.getChildAt(0);
                String tag = (String) v.getTag();
                if (tag != null && tag.equals("listview")) {
                    mMainLayout.removeView(v);
                    mMainLayout.addView(v);
                }
            }

        } else {
            keyBoardVert(false, input, true);
            keyBoardHori(true, input);

            updateShadow(Constants.KEYBOARD_LAYOUT_HORIZONTAL, mKeypadAtRight);
        }
    }

    /**
     * 横键盘fragment初始化逻辑
     *
     * @param visible
     * @param text
     */
    private void keyBoardHori(boolean visible, String text) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // mVerticalPadScrollView.setVisibility(visible ? View.GONE : View.VISIBLE);
        mKeypadHoriContainer.setVisibility(visible ? View.VISIBLE : View.GONE);
        // 由于fragment状态的保存会导致输入框查询字共享和无法消失的问题有冲突，现在先解决查询字共享的问题
        // 横向键盘无法消失的问题另外找办法解决
        //        if (visible) {
        //            Bundle bundle = new Bundle();
        //            bundle.putParcelable(DATA, getIntent());
        //
        //            String filterText = null;
        //            if (mKeyboardVertFrag != null && !TextUtils.isEmpty(
        //                    filterText = mKeyboardVertFrag.getFilterText())) {
        //                bundle.putString(FILTER_CHAR, filterText);
        //            }
        //
        //            if (mKeyboardHoriFrag == null) {
        //                mKeyboardHoriFrag = KeyboardHoriFrag.newInstance(bundle);
        //                // use replace because the bug of keypad not
        //                // disappear when click R.id.isdisplay_dialpadunder
        //                // bug cause: the fragment oncreateview called twice, this
        //                // modify
        //                // suggestion comes from stack over flow
        //                ft.replace(R.id.keypad_hori_container, mKeyboardHoriFrag);
        //            } else if (mKeyboardHoriFrag.isDetached()) {
        //                mKeyboardHoriFrag.getArguments().putAll(bundle);
        //                ft.attach(mKeyboardHoriFrag);
        //            }
        //        } else if (mKeyboardHoriFrag != null) {
        //            ft.detach(mKeyboardHoriFrag);
        //        }
        if (visible) {
            Bundle bundle = new Bundle();
            bundle.putParcelable(DATA, getIntent());
            if (text != null) {
                bundle.putString("input", text);
            }
            if (mKeyboardHoriFrag == null) {
                mKeyboardHoriFrag = KeyboardHoriFrag.newInstance(bundle);
            }
            ft.replace(R.id.keypad_hori_container, mKeyboardHoriFrag);
        } else if (mKeyboardHoriFrag != null) {
            ft.remove(mKeyboardHoriFrag);
        }
        ft.commitAllowingStateLoss();
    }


    Bundle changebundle;

    /**
     * 竖键盘fragment初始化逻辑
     *
     * @param visible
     * @param text
     */
    private void keyBoardVert(boolean visible, String text, boolean showdepartment) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        mKeypadVertContainer.setVisibility(visible ? View.VISIBLE : View.GONE);

        if (showdepartment == false) {
            if (mTreeFrag != null) {
                //ft.remove(mTreeFrag);
                ft.hide(mTreeFrag);

            }

            Bundle bundle = new Bundle();
            bundle.putParcelable(DATA, getIntent());
            if (text != null) {
                bundle.putString("input", text);
            }
            if (mKeyboardVertFrag == null) {
                mKeyboardVertFrag = KeyboardVertFrag.newInstance(bundle);
                //                mKeyboardVertFrag = KeyboardVertFrag.newInstance();
            } else {
                if (mListStatus != ListStatus.ENUM_SHOW_CONTACT_INFO) {
                    Intent intent = new Intent();
                    intent.putExtra(Constants.INTENT_TAG_ID, "0");
                    intent.putExtra(Constants.INTENT_TAG_NAME, "全部成员");
                    intent.putExtra("tag_count", "");
                    intent.putExtra("group_id", groupId);
                    intent.putExtra("group_name", groupName);
                    intent.putExtra("contact_count", contactCount);
                    intent.setAction("structure_tag_click");
                    if (mTreeFrag == null) {
                        if (text == null) {
                            CloudDialerActivity.instance.ListRefresh(intent, Activity.RESULT_OK, null);
                        } else {
                            CloudDialerActivity.instance.ListRefresh(intent, -2, null);
                        }
                    } else {
                        if (text == null) {
                            CloudDialerActivity.instance.ListRefresh(intent, Activity.RESULT_OK, mTreeFrag.root);
                        } else {
                            CloudDialerActivity.instance.ListRefresh(intent, -2, mTreeFrag.root);
                        }
                    }
                    textChanged(null, 0);
                }
            }


            if (!mKeyboardVertFrag.isAdded()) {
                ft.add(R.id.keypad_vert_container, mKeyboardVertFrag);
            }

            ft.show(mKeyboardVertFrag);


        } else if (mKeyboardVertFrag != null) {
            //ft.remove(mKeyboardVertFrag);
            ft.hide(mKeyboardVertFrag);
            if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_GROUP_MEMBER) != 0) {

            } else if (mListStatus != ListStatus.ENUM_SHOW_CONTACT_INFO) {
                if (changebundle == null) {
                    changebundle = new Bundle();
                }
                changebundle.putString("group_id", groupId);
                changebundle.putString("group_name", groupName);
                // changebundle.putString("pid", "");
                // changebundle.putString("group_img", groupImg);
                changebundle.putInt("group_type", groupType);
                changebundle.putString("user_type", userType);
                changebundle.putInt("contact_count", contactCount);
                changebundle.putString("contact_id", contactId);
                changebundle.putIntegerArrayList("clickPosition", clickPosition);
                changebundle.putInt("currentPosition", currentPosition);

                //   }
            }


            if (mTreeFrag == null) {
                mTreeFrag = TreeFrag.newInstance(changebundle);
            }

            if (!mTreeFrag.isAdded()) {
                ft.add(R.id.keypad_vert_container, mTreeFrag);
            }

            ft.show(mTreeFrag);

            if (mTreeFrag != null) {

                mTreeFrag.updateCurrentItem();
            }
            if ("3".equals(userType)) {
                boolean isFirst = mPreferenceUtil.getBoolean("structure_add_v1", true);
                if (isFirst) {
                    mHelpStructureAdd.setVisibility(View.VISIBLE);
                } else {
                    mHelpStructureAdd.setVisibility(View.GONE);
                }
            }
        }
        ft.commitAllowingStateLoss();

    }


    /**
     * 初始化皮肤数据
     */
    private void initSkin() {
        mIsHaveTone = mPreferenceUtil.getInt(PreferenceUtil.CONTACT_IS_HAVESOUND,
                Constants.SOUND_CLOSE);
        mKeyboardOri = mPreferenceUtil.getInt(PreferenceUtil.CONTACT_KEYBOARD_LAYOUTORIENTATION,
                Constants.KEYBOARD_LAYOUT_VERTICAL);
        String path = mPreferenceUtil.getString(PreferenceUtil.CONTACT_KEYBOARD_PACKAGENAME, "local");
        GetSkinResource getSkinResource = new GetSkinResource(this);
        boolean isT9 = mPreferenceUtil.getBoolean(PreferenceUtil.IS_T9, true);
//        boolean isT9 = false;//false时显示字母键盘
        if (mKeyboardOri == Constants.KEYBOARD_LAYOUT_HORIZONTAL) {
            mHorizSkin = getSkinResource.getAllHorizSkinData(this, path);
        } else {


            if (mVertySkin == null) {
                mVertySkin = new SkinVertyData();

	            /*
                if (isT9) {
	                mVertySkin = getSkinResource.getVertT9SkinData(mVertySkin, this, path);
	            } else {
	                mVertySkin = getSkinResource.getVertABCSkinData(mVertySkin, this, path);
	            }
	            */
                mVertySkin = getSkinResource.getVertT9SkinData(mVertySkin, this, path);

            } else {
                mVertySkin = getSkinResource.getVertT9SkinData(mVertySkin, this, path);
            }


            if (mVertySkin2 == null) {
                mVertySkin2 = new SkinVertyData();

	            /*
                if (isT9) {
	                mVertySkin = getSkinResource.getVertT9SkinData(mVertySkin, this, path);
	            } else {
	                mVertySkin = getSkinResource.getVertABCSkinData(mVertySkin, this, path);
	            }
	            */
                mVertySkin2 = getSkinResource.getVertABCSkinData(mVertySkin2, this, path);

            } else {
                mVertySkin2 = getSkinResource.getVertABCSkinData(mVertySkin2, this, path);
            }

            //  }
//            else
//            {
//            	getSkinResource.loadDefaultVertCommonPic(this, mVertySkin);
//            }


        }
        mSkinCommon = getSkinResource.loadCommon(this, path, mIsHaveTone);
    }

    private View mKeypadHoriContainer;
    private View mKeypadVertContainer;

    /**
     * 初始化键盘的布局容器
     */
    private void initRootViewInKeyboard() {
        mKeypadVertContainer = findViewById(R.id.keypad_vert_container);
        mKeypadHoriContainer = findViewById(R.id.keypad_hori_container);
        //mVerticalPadScrollView = (VerticalKeyPadScrollLayout) findViewById(R.id.vertical_scroll_layout);
    }

    /**
     * 设置键盘以外其它元素的皮肤数据
     *
     * @param skin
     */
    public void setComponet(final SkinCommonData skin) {
        if (skin.listBgBitmap == null) {
            if (skin.listBgColor == 0) {
                // 设置完整背景（设置部分背景会闪烁）
                mContactsListView.setBackgroundColor(Color.WHITE);
                //add by lk for pad back
                //mVerticalPadScrollView.setBackgroundColor(Color.WHITE);
            } else {
                mContactsListView.setBackgroundColor(skin.listBgColor);
                mContactsListView.setCacheColorHint(skin.listBgColor);
                //add by lk for pad back
                //mVerticalPadScrollView.setBackgroundColor(skin.listBgColor);
            }
        } else {
            mContactsListView.setCacheColorHint(Color.TRANSPARENT);
            mContactsListView.setBackgroundDrawable(skin.listBgBitmap);
            //竖键盘整体背景add by lk
            //mVerticalPadScrollView.setBackgroundDrawable(skin.listBgBitmap);
        }

        float density = getResources().getDisplayMetrics().density;
        int dividerHeight = (int) (1 * density);

        if (skin.listDividerColor == 0) {
            mContactsListView.setDivider(new ColorDrawable(0x99b2b2b2));
        } else {
            mContactsListView.setDivider(new ColorDrawable(skin.listDividerColor));
        }

        if (skin.listTextHightLightColor == 0) {
            skin.listTextHightLightColor = Color.BLUE;
        }

        if (skin.listSectionColor == 0) {
            skin.listSectionColor = Color.parseColor("#f1b6bfc6");
        }

//        mContactsListView.setDividerHeight(dividerHeight);
        //mContactsListView.setHeaderViewColorAndTextColor(skin.listSectionColor, skin.barTitleColor);

        mContactEntryAdapter.setSkin(skin);
        mContactEntryAdapter.setColor(skin.nameColor, skin.jobTitleColor, skin.phoneColor,
                skin.listTextHightLightColor, skin.listSectionColor, skin.barTitleColor);
        mContactEntryAdapter.setNoNameDrawable(skin.noNameBitmap);
        mContactEntryAdapter.notifyDataSetChanged();
        //        if (mCloudContactAdapter != null) {
        //            mCloudContactAdapter.setColor(skin.nameColor, skin.jobTitleColor, skin.phoneColor,
        //                    skin.listTextHightLightColor, skin.listSectionColor, skin.barTitleColor);
        //            mCloudContactAdapter.notifyDataSetChanged();
        //        }
        //        mTvListName.setTextColor(mSkinCommon.barTitleColor);
        mMainTitle.setBackgroundDrawable(skin.mainTitleBgResid);// 设计稿中暂未设置键盘顶部titlebar颜色，need makesure
        mPreferenceUtil.save(PreferenceUtil.CONTACT_KEYBOARD_THEMECOLOR, mKeyboardThemeColor);
        //        mPreferenceUtil.save(PreferenceUtil.CONTACT_KEYBOARD_PACKAGENAME, skin.mSkinPkgName);
    }

    /**
     * 拖动横键盘
     *
     * @param distance
     */
    public void scrollHoriPadView(float distance) {
        if (mKeypadHoriContainer != null) {
            int left = (int) (mKeypadHoriContainer.getX() + distance);
            int top = (int) mKeypadHoriContainer.getY();
            int right = left + Constants.dip2px(mContext, 320);
            int bottom = top + mKeypadHoriContainer.getHeight();
            if (left < 0) {
                left = 0;
                right = Constants.dip2px(mContext, 320);
            }
            if (right > mMainLayout.getWidth()) {
                right = mMainLayout.getWidth();
                left = mMainLayout.getWidth() - Constants.dip2px(mContext, 320);
            }
            mKeypadHoriContainer.layout(left, top, right, bottom);
        }
    }

    /**
     * 保存横键盘的最后位置(left)
     */
    public void saveHoriKbLastPosition() {
        int left = (int) mKeypadHoriContainer.getX();
        mPreferenceUtil.save(PreferenceUtil.HORI_KEYBOARD_LAST_LEFT, left);
    }


    /**
     * 根据当前的位置左边或者右边 显示 控制显示t9或者全字母键盘 的ImageButton
     *
     * @param isRight
     */
    private void controlDisplayImageButtonForT9OrAllwords(boolean isRight) {
        mKeyboardVertFrag.controlDisplayImageButtonForT9OrAllwords(isRight);
        updateShadow(Constants.KEYBOARD_LAYOUT_VERTICAL, isRight);
    }

    private void updateShadow(int keyboardOri, boolean isKeyRight) {
        if (keyboardOri == Constants.KEYBOARD_LAYOUT_VERTICAL) {
            if (leftShadowView == null) {
                leftShadowView = mMainLayout.findViewById(R.id.left_shadow);
                leftShadow = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT,
                        new int[]{
                                Color.argb(100, 0, 0, 0), Color.argb(80, 0, 0, 0),
                                Color.argb(10, 0, 0, 0), Color.argb(0, 0, 0, 0)
                        }
                );
                leftShadow.setGradientType(GradientDrawable.LINEAR_GRADIENT);
                leftShadowView.setBackgroundDrawable(leftShadow);

                rightShadowView = mMainLayout.findViewById(R.id.right_shadow);
                rightShadow = new GradientDrawable(GradientDrawable.Orientation.RIGHT_LEFT,
                        new int[]{
                                Color.argb(100, 0, 0, 0), Color.argb(80, 0, 0, 0),
                                Color.argb(10, 0, 0, 0), Color.argb(0, 0, 0, 0)
                        }
                );
                rightShadow.setGradientType(GradientDrawable.LINEAR_GRADIENT);
                rightShadowView.setBackgroundDrawable(rightShadow);
            }

            if (isKeyRight) {
                rightShadowView.setVisibility(View.VISIBLE);
                leftShadowView.setVisibility(View.GONE);
            } else {
                rightShadowView.setVisibility(View.GONE);
                leftShadowView.setVisibility(View.VISIBLE);
            }
            if (horizonShadowView != null)
                horizonShadowView.setVisibility(View.GONE);
        } else {
            if (horizonShadowView == null) {
                horizonShadowView = findViewById(R.id.hshadow);
                horizonShadow = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP,
                        new int[]{
                                Color.argb(100, 0, 0, 0), Color.argb(80, 0, 0, 0),
                                Color.argb(10, 0, 0, 0), Color.argb(0, 0, 0, 0)
                        }
                );
                horizonShadow.setGradientType(GradientDrawable.LINEAR_GRADIENT);
                horizonShadowView.setBackgroundDrawable(horizonShadow);
            }

            if (leftShadowView != null) {
                leftShadowView.setVisibility(View.GONE);
                rightShadowView.setVisibility(View.GONE);
            }
            //            horizonShadowView.setVisibility(View.VISIBLE);
        }
    }

    public void destroryDrawingCache(ViewGroup vg) {
        vg.destroyDrawingCache();
        int count = vg.getChildCount();
        for (int i = 0; i < count; i++) {
            View v = vg.getChildAt(i);
            if (v instanceof ViewGroup) {
                destroryDrawingCache((ViewGroup) v);
            } else {
                v.destroyDrawingCache();
            }
        }
    }

    /**
     *
     */
    public class BackgroundHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int msgId = msg.what;
            switch (msgId) {
                case Constants.FRESH_SEND_BUTTON_NUMBER: {
                    int size = 0;
                    if (mCloudContactAdapter != null && ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_CLOUD_CHAT_MEMBER) != 0) || ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_GROUP_MEMBER) != 0) || ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_MANAGER_ADD) != 0) || ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_MEMBER_DELETE) != 0) || ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_EVENT_ADD_RECEIVER) != 0) || ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_SCHEDULE_MANAGER) != 0) || ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ATTENDANCE_MEMBER) != 0) || ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_APPROVAL_LEADER) != 0) || ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_WEEKLY_MANAGER) != 0)) {
                        size = mCloudContactAdapter.getSelectedContacts().size();
                        String btnText = "已选";//mBtnSend.getText().toString();
                        /*
                        int index = btnText.indexOf("(");
                        if (index == -1) {
                            //mBtnSend.setText(btnText + "(" + size + ")");

                            mShowModleChiceView.setText(btnText + "(" + size + ")");
                        } else {
                            String replace = "(" + size + ")";
                            btnText = btnText.replaceAll("\\([\\d]*\\)", replace);
                            //mBtnSend.setText(btnText);
                            mShowModleChiceView.setText(btnText);
                        }
                        */
                        if (size != 0) {
                            mShowModleChiceView.setText(btnText + "(" + size + ")");
                        } else {
                            mShowModleChiceView.setText(btnText);
                        }

                    } else {
//                            size = mContactEntryAdapter.getSelectedContacts().size();
//                            if (size == 0) {
                        size = mContactEntryAdapter.getSelectedContactIds().size();
//                            }
                        // String btnText = mBtnSend.getText().toString();
                        String btnText = "已选";//mBtnSend.getText().toString();
                        /*
                        int index = btnText.indexOf("(");
                        if (index == -1) {
                            //mBtnSend.setText(btnText + "(" + size + ")");
                            mShowModleChiceView.setText(btnText + "(" + size + ")");
                        } else {
                            String replace = "(" + size + ")";
                            btnText = btnText.replaceAll("\\([\\d]*\\)", replace);
                            //mBtnSend.setText(btnText);
                            mShowModleChiceView.setText(btnText);
                        }
                        */
                        if (size != 0) {
                            mShowModleChiceView.setText(btnText + "(" + size + ")");
                        } else {
                            mShowModleChiceView.setText(btnText);
                        }
                    }
                }
                break;
                case Constants.BATCH_OPERATION_MSG: {
                    if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_CLOUD_CHAT_MEMBER) != 0) {// 从云号码群添加成员到聊天小组
                       /* JSONArray jsonArray = new JSONArray();
                        for (int i = 0; i < mCloudContactAdapter.getSelectedContacts().size(); i++) {
                            ChatContact chatContact = mCloudContactAdapter.getSelectedContacts().get(i);
                            try {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("user_name", chatContact.getUserName());
                                jsonObject.put("user_image", chatContact.getUserImg());
                                jsonObject.put("contact_id", chatContact.getContactId());
                                jsonObject.put("user_id", chatContact.getUserId());
                                jsonArray.put(jsonObject);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if (mCloudContactAdapter.getSelectedContacts().size() == 0) {
                            Toast.makeText(mContext, "请至少选择一个联系人！", Toast.LENGTH_SHORT).show();
                        } else {
                            if (StringUtil.isEmpty(chatGroupId)) {
                                addChatGroupContactList(jsonArray);//创建小组
                                mMemberCount = jsonArray.length() + 1 + "";
                            } else {
                                addMemberToChatGroup(jsonArray);//给已存在的小组添加成员
                            }
                            quitBatchOperation(true, true);
                        }*/
                        List<String> startDisList = new ArrayList<>();
                        String disName="";
                        StringBuilder sb = new StringBuilder();
                        int count = 0;
                        if (chatContacts != null && mCloudContactAdapter.getSelectedContacts().size() <= chatContacts.size()) {
                            for (int i = 0; i < chatContacts.size(); i++) {
                                for (ChatContact chatContact : mCloudContactAdapter.getSelectedContacts()) {
                                    if (chatContacts.get(i).equals(chatContact)) {
                                        count++;
                                        break;
                                    }
                                }
                                if (count == mCloudContactAdapter.getSelectedContacts().size()) {
                                    break;
                                }
                            }
                        }
                        for (ChatContact chatContact : mCloudContactAdapter.getSelectedContacts()) {
                            sb.append(chatContact.getUserName());
                            sb.append(",");
                            startDisList.add(chatContact.getUserId());
                        }

                        String str = sb.toString();
                        if(str.length()>0){
                            disName = str.substring(0, str.length() - 1);
                        }
                        if (mCloudContactAdapter.getSelectedContacts().size() == 0) {
                            Toast.makeText(mContext, "请至少选择一个联系人！", Toast.LENGTH_SHORT).show();
                        } else if (count == mCloudContactAdapter.getSelectedContacts().size()) {
                            Toast.makeText(CloudDialerActivity.this, "您选择的人已加入此群组，请重新选择", Toast.LENGTH_LONG).show();
                            mCloudContactAdapter.clearSelected();
                            mCloudContactAdapter.notifyDataSetChanged();
                        } else {
                            if (isSingle) {//单聊创建群聊
                                for (int i = 0; i < chatContacts.size(); i++) {
                                    disName = disName + "," + chatContacts.get(i).getUserName();
                                    startDisList.add(chatContacts.get(i).getUserId());
                                }
                                RongIM.getInstance().createDiscussion(disName, startDisList, new RongIMClient.CreateDiscussionCallback() {
                                    @Override
                                    public void onSuccess(String s) {
                                        Log.d("createDiscussion", "onSuccess" + s);
                                        RongIM.getInstance().startDiscussionChat(CloudDialerActivity.this, s, "");
                                    }

                                    @Override
                                    public void onError(RongIMClient.ErrorCode errorCode) {
                                        Log.d("createDiscussion", errorCode.getValue() + "");
                                    }
                                });
                            } else {
                                if (StringUtil.isEmpty(chatGroupId)) {//发起群聊
                                    RongIM.getInstance().createDiscussion(disName, startDisList, new RongIMClient.CreateDiscussionCallback() {
                                        @Override
                                        public void onSuccess(String s) {
                                            Log.d("createDiscussion", "onSuccess" + s);
                                            RongIM.getInstance().startDiscussionChat(CloudDialerActivity.this, s, "");
                                        }

                                        @Override
                                        public void onError(RongIMClient.ErrorCode errorCode) {
                                            Log.d("createDiscussion", errorCode.getValue() + "");
                                        }
                                    });

                                } else {//群聊添加成员
                                    RongIMClient.getInstance().addMemberToDiscussion(chatGroupId, startDisList, new RongIMClient.OperationCallback() {
                                        @Override
                                        public void onSuccess() {
                                            Intent intent = new Intent(CloudDialerActivity.this, ChatGroupDetailActivity.class);
                                            intent.putExtra("TargetId", chatGroupId);
                                            intent.putExtra("isSingle", false);
                                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                            startActivity(intent);
                                        }

                                        @Override
                                        public void onError(RongIMClient.ErrorCode errorCode) {

                                        }
                                    });

                                }
                            }

                            quitBatchOperation(true, true);
                        }

                    } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_EVENT_ADD_RECEIVER) != 0) {// 从云号码群添加事件收件人
                        if (mCloudContactAdapter.getSelectedContacts().size() == 1 && mCloudContactAdapter.getSelectedContacts().get(0).getUserId().equals(mUid)) {
                            Toast.makeText(CloudDialerActivity.this, "请选择除自己以外的人员", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        JSONArray jsonArray = new JSONArray();
                        if (eventReceiver != null && eventReceiver.length() > 0) {
                            try {
                                JSONArray jsonArray1 = new JSONArray(eventReceiver);
                                for (int i = 0; i < jsonArray1.length(); i++) {
                                    JSONObject jsonObject = jsonArray1.getJSONObject(i);
                                    jsonArray.put(jsonObject);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        for (int i = 0; i < mCloudContactAdapter.getSelectedContacts().size(); i++) {
                            ChatContact chatContact = mCloudContactAdapter.getSelectedContacts().get(i);
                            try {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("user_id", chatContact.getUserId());
                                jsonObject.put("user_name", chatContact.getUserName());
                                jsonObject.put("user_image", chatContact.getUserImg());
                                jsonObject.put("contact_id", chatContact.getContactId());
                                boolean isSame = false;
                                for (int j = 0; j < jsonArray.length(); j++) {
                                    if (jsonArray.getJSONObject(j).getString("user_id").equals(jsonObject.getString("user_id")) && jsonArray.getJSONObject(j).getString("user_name").equals(jsonObject.getString("user_name")) && jsonArray.getJSONObject(j).getString("user_image").equals(jsonObject.getString("user_image"))) {
                                        isSame = true;
                                        break;
                                    }
                                }
                                if (!isSame) {
                                    jsonArray.put(jsonObject);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        Intent intent = new Intent();
                        if (mCloudContactAdapter.getSelectedContacts().size() == 0) {
                            Toast.makeText(mContext, "请至少选择一个联系人！", Toast.LENGTH_SHORT).show();
                        } else {
                            if (StringUtil.isEmpty(eventId)) {
                                if ("1".equals(((DialerApp) getApplication()).getmEventToWhere())) {
                                    intent.setClass(CloudDialerActivity.this, CreateNewEventActivity.class);
                                } else {
                                    intent.setClass(CloudDialerActivity.this, CustomEventActivity.class);
                                }
                                mEventData.setReceiver(jsonArray.toString());
                                mBundle.putSerializable("event_bundle", mEventData);
                                intent.putExtra("event_msg", mBundle);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                                mBatchOperationType = 0;
                            } else {
                                addReceiverToEvent(jsonArray.toString());
                            }

                        }
                    } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_GROUP_MEMBER) != 0) {//设置云号码圈成员
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < mCloudContactAdapter.getSelectedContacts().size(); i++) {
                            ChatContact chatContact = mCloudContactAdapter.getSelectedContacts().get(i);
                            sb.append(chatContact.getContactId() + ",");
                        }
                        String contactIds = "";
                        if (sb.length() > 0) {
                            contactIds = sb.substring(0, sb.length() - 1);
                        }
                        setGroupContact(contactIds);
//                        quitBatchOperation(true, true);

                    } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_MANAGER_ADD) != 0) {//号码簿设置管理员
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < mCloudContactAdapter.getSelectedContacts().size(); i++) {
                            ChatContact chatContact = mCloudContactAdapter.getSelectedContacts().get(i);
                            sb.append(chatContact.getContactId() + ",");
                        }
                        String contactIds = "";
                        if (sb.length() > 0) {
                            contactIds = sb.substring(0, sb.length() - 1);
                        }
                        if (contactIds.length() <= 0) {
                            Toast.makeText(mContext, "请至少选择一个联系人！", Toast.LENGTH_SHORT).show();
                        } else {
                            setGroupManager(contactIds);
                            quitBatchOperation(true, true);
                        }
                    } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_MEMBER_DELETE) != 0) {//批量删除号码圈成员
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < mCloudContactAdapter.getSelectedContacts().size(); i++) {
                            ChatContact chatContact = mCloudContactAdapter.getSelectedContacts().get(i);
                            sb.append(chatContact.getContactId() + ",");
                        }
                        String contactIds = "";
                        if (sb.length() > 0) {
                            contactIds = sb.substring(0, sb.length() - 1);
                        }
                        if (contactIds.length() <= 0) {
                            Toast.makeText(mContext, "请至少选择一个联系人！", Toast.LENGTH_SHORT).show();
                        } else {
                            deleteGroupMember(contactIds);
                            quitBatchOperation(true, true);
                        }

                    } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_SCHEDULE_MANAGER) != 0) {// 从云号码圈添加日程管理员
                        StringBuilder userIds = new StringBuilder();
                        for (int i = 0; i < mCloudContactAdapter.getSelectedContacts().size(); i++) {
                            ChatContact chatContact = mCloudContactAdapter.getSelectedContacts().get(i);
                            userIds.append(chatContact.getUserId() + ",");
                        }
                        if (mCloudContactAdapter.getSelectedContacts().size() == 0) {
                            Toast.makeText(mContext, "请至少选择一个联系人！", Toast.LENGTH_SHORT).show();
                        } else {
                            addScheduleManager(userIds.substring(0, userIds.length() - 1));
                            quitBatchOperation(true, true);
                        }
                    } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ATTENDANCE_MEMBER) != 0) {// 从云号码圈添加考勤成员
                        JSONArray jsonArray = null;
                        if (StringUtil.isEmpty(attendanceData.getMembers())) {
                            jsonArray = new JSONArray();
                        } else {
                            try {
                                jsonArray = new JSONArray(attendanceData.getMembers());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        for (int i = 0; i < mCloudContactAdapter.getSelectedContacts().size(); i++) {
                            ChatContact chatContact = mCloudContactAdapter.getSelectedContacts().get(i);
                            try {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("contact_name", chatContact.getUserName());
                                jsonObject.put("contact_id", chatContact.getContactId());
                                jsonObject.put("user_id", chatContact.getUserId());
                                jsonObject.put("user_image", chatContact.getUserImg());
                                boolean isSame = false;
                                for (int j = 0; j < jsonArray.length(); j++) {
                                    if ("0".equals(jsonObject.getString("user_id"))) {
                                        if (jsonArray.getJSONObject(j).getString("contact_name").equals(jsonObject.getString("contact_name")) && jsonArray.getJSONObject(j).getString("contact_id").equals(jsonObject.getString("contact_id"))) {
                                            isSame = true;
                                            break;
                                        }
                                    } else {
                                        if (jsonArray.getJSONObject(j).getString("user_id").equals(jsonObject.getString("user_id")) && jsonArray.getJSONObject(j).getString("contact_name").equals(jsonObject.getString("contact_name"))) {
                                            isSame = true;
                                            break;
                                        }
                                    }
                                }
                                if (!isSame) {
                                    jsonArray.put(jsonObject);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if (mCloudContactAdapter.getSelectedContacts().size() == 0) {
                            Toast.makeText(mContext, "请至少选择一个联系人！", Toast.LENGTH_SHORT).show();
                        } else {
                            attendanceData.setMembers(jsonArray.toString());
                            attendanceData.setMemberCount(jsonArray.length() + "");

                            Intent intent = new Intent(CloudDialerActivity.this, AttendanceSettingActivity.class);
                            intent.putExtra("attendanceData", attendanceData);
                            intent.putExtra("group_id", attendanceData.getGroupId());
                            intent.putExtra("tag_id", "0");
                            intent.putExtra("tag_name", tagName);
                            intent.putExtra("group_name", groupName);
                            intent.putExtra("user_type", userType);
                            intent.putExtra("contact_id", contactId);
                            intent.putExtra("where", "cloud");
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            quitBatchOperation(true, true);
                        }
                    } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_APPROVAL_LEADER) != 0) {//
                        if (mCloudContactAdapter.getSelectedContacts().size() == 0) {
                            Toast.makeText(mContext, "请至少选择一个联系人！", Toast.LENGTH_SHORT).show();
                        } else {
                            StringBuilder userIds = new StringBuilder();
                            for (int i = 0; i < mCloudContactAdapter.getSelectedContacts().size(); i++) {
                                ChatContact chatContact = mCloudContactAdapter.getSelectedContacts().get(i);
                                userIds.append(chatContact.getContactId() + ",");
                            }
                            addApprovalManager(userIds.substring(0, userIds.length() - 1));
                            quitBatchOperation(true, true);
                        }
                    } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_WEEKLY_MANAGER) != 0) {//
                        if (mCloudContactAdapter.getSelectedContacts().size() == 0) {
                            Toast.makeText(mContext, "请至少选择一个联系人！", Toast.LENGTH_SHORT).show();
                        } else {
                            StringBuilder userIds = new StringBuilder();
                            for (int i = 0; i < mCloudContactAdapter.getSelectedContacts().size(); i++) {
                                ChatContact chatContact = mCloudContactAdapter.getSelectedContacts().get(i);
                                userIds.append(chatContact.getUserId() + ",");
                            }
                            addWeeklyManager(userIds.substring(0, userIds.length() - 1));
                            quitBatchOperation(true, true);
                        }
                    } else {
                        final ArrayList<Long> selectedPeople = mContactEntryAdapter
                                .getSelectedContactIds();
                        // judge if send business card
                        if (((mBatchOperationType & (1 << Constants.CHECKBOX_STATUS_BUSINESSCARD)) != 0)
                                || ((mBatchOperationType & (1 << Constants.CHECKBOX_STATUS_BUSINESSCARD_WITHSMS)) != 0)) {
                            Iterator<Long> it = selectedPeople.iterator();
                            JSONArray arrs = new JSONArray();
                            StringBuffer sb = new StringBuffer();
                            while (it.hasNext()) {
                                long contactId = it.next();
                                JSONObject obj = new JSONObject();
                                String firstMobilePhoneNumber = ContactsDBReader
                                        .getFirstMobilePhoneNumber(CloudDialerActivity.this,
                                                contactId, true);
                                                            /*
                                                             * if (firstMobilePhoneNumber != null) {
                                                             * firstMobilePhoneNumber = numberArea
                                                             * .replaceIpCall(firstMobilePhoneNumber); }
                                                             */

                                if (!StringUtil.isEmpty(firstMobilePhoneNumber)) {
                                    sb.append(firstMobilePhoneNumber + ",");
                                    if (selectedPeople.size() > 10) {
                                        try {
                                            obj.put(contactId + "", firstMobilePhoneNumber);
                                        } catch (JSONException e) {
                                            // Auto-generated catch
                                            // block
                                            e.printStackTrace();
                                        }
                                    }
                                }
                                arrs.put(obj);
                            }
                            long contactId = 0;
                            contactId = mShareContactId;
                            if (selectedPeople.size() > 10) {
                                if (!checkSIMCard()) {
                                    Toast.makeText(mContext, R.string.simcard_not_inserted,
                                            Toast.LENGTH_LONG).show();
                                    return;
                                }
                                PreferenceUtil mPreferenceUtil = PreferenceUtil
                                        .getInstance(mContext);
                                int isTwoSim = mPreferenceUtil.get(PreferenceUtil.IS_TWO_SIM,
                                        Integer.class);

                                if (isTwoSim == 1) {
                                    String twoSimPackage = mPreferenceUtil.getString(
                                            PreferenceUtil.TWO_SIM_PACKAGE, null);
                                    boolean isHaveInstalled = false;
                                    MsgCenter mc = MsgCenter.getInstance(mContext);
                                    PackageManager pm = getPackageManager();
                                    try {
                                        pm.getApplicationIcon(twoSimPackage);
                                        isHaveInstalled = true;
                                    } catch (PackageManager.NameNotFoundException e) {
                                        isHaveInstalled = false;
                                    }
                                    if (isHaveInstalled) {
                                        Intent intent = new Intent();
                                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                        intent.setComponent(new ComponentName(twoSimPackage,
                                                twoSimPackage + ".BatchSendSmsActivity"));
                                        intent.setAction(Constants.TWO_SIM_PLUGIN);
                                        //BatchSendSmsActivity群发短信页面
                                        intent.putExtra(BatchSendSmsActivity.NUMBERS_KEY,
                                                arrs.toString());
                                        startActivity(intent);
                                    } else {
                                        Intent intent = new Intent(mContext,
                                                BatchSendSmsActivity.class);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                        intent.putExtra(BatchSendSmsActivity.NUMBERS_KEY,
                                                arrs.toString());
                                        startActivity(intent);
                                        long flag = mc.typeMsgExist(0,
                                                AsynHttpClient.SYNC_CHANNEL_HAVE_TWOSIM_PLUGIN);
                                        if (flag == -1) {
                                            MsgCenter.MsgDataItem item = new MsgCenter.MsgDataItem();
                                            item.cloudId = 0;
                                            item.phoneNum = null;
                                            item.isReaded = CloudContactsDB.MsgItem.UNREAD;
                                            item.dateTime = System.currentTimeMillis();
                                            item.execCode = AsynHttpClient.SYNC_CHANNEL_HAVE_TWOSIM_PLUGIN;
                                            item.displayText = "有双卡插件需要安装";
                                            item.argList = "";
                                            item.msgTypeDrawableId = R.drawable.ic_msg_type;
                                            item.nextActionDrawableId = -1;
                                            mc.addNewMsg(item);
                                        } else {
                                            MsgCenter.MsgDataItem item = mc.getMsgItem(flag);
                                            item.isReaded = CloudContactsDB.MsgItem.UNREAD;
                                            item.msgTypeDrawableId = R.drawable.ic_msg_type;
                                            mc.updateMsgReaded(item);
                                        }
                                    }
                                } else {
                                    Intent intent = new Intent(mContext, BatchSendSmsActivity.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                    intent.putExtra(BatchSendSmsActivity.NUMBERS_KEY,
                                            arrs.toString());
                                    String type = mPreferenceUtil.getString(
                                            PreferenceUtil.TWO_SIM_TYPE, null);
                                    intent.putExtra("type", type);
                                    startActivity(intent);
                                    quitBatchOperation(true, true);
                                }
                            } else if (selectedPeople.size() == 0) {
                                Toast.makeText(mContext, "请至少选择一个联系人！", Toast.LENGTH_SHORT).show();
                            } else {

                                if (sb != null && !(sb.equals("")) && sb.length() != 0) {

                                    sb.deleteCharAt(sb.length() - 1);
                                }

                                if (sb.length() > 0) {
                                    if (contactId != -1) {
                                        if (contactId == 222) {
                                            CommonCodeUtil.launchSendMessage(
                                                    CloudDialerActivity.this, sb.toString(),
                                                    "姓名：" + mShareName + "\n" + mSharePhone + "\n" + "通过“团队”发送"
                                            );
                                        } else {
                                            CommonCodeUtil.launchSendMessage(
                                                    CloudDialerActivity.this, sb.toString(),
                                                    ContactsSend.getFormatedContact(
                                                            CloudDialerActivity.this, contactId)
                                            );
                                        }
                                    }
                                } else {
                                    if (contactId != -1) {
                                        CommonCodeUtil.launchSendMessage(
                                                CloudDialerActivity.this, "", ContactsSend
                                                        .getFormatedContact(
                                                                CloudDialerActivity.this,
                                                                contactId)
                                        );
                                    }
                                }
                                quitBatchOperation(true, true);
                            }

                        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_CLOUD_UPLOAD) != 0) {
                            if ((selectedGroup.groupType & CreateGroupActivity.REQUIRE_AUDIT_FOR_ADD_CONTACT) != 0) {
                                AllDialogUtil dialogUtil = AllDialogUtil
                                        .getInstance(CloudDialerActivity.this);
                                dialogUtil.titleMsgBtnStyle("提示", "该群组添加联系人需要审核，请耐心等候您的提交结果！",
                                        "确定");
                                dialogUtil
                                        .setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

                                            @Override
                                            public void onConfirmClick(Dialog lDialog) {
                                                lDialog.dismiss();
                                                uploadCloudContact(mContactEntryAdapter
                                                        .getSelectedContactIds());
                                            }

                                            @Override
                                            public void onCancelClick(Dialog lDialog) {
                                            }
                                        });
                            } else {
                                if (mContactEntryAdapter.getSelectedContacts().size() == 0 && mContactEntryAdapter.getSelectedContactIds().size() == 0) {
                                    Toast.makeText(mContext, "请至少选择一个联系人！", Toast.LENGTH_SHORT).show();
                                } else {
                                    uploadCloudContact(mContactEntryAdapter.getSelectedContactIds());
                                }

                            }
                        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_BLACK_LIST) != 0
                                || (mBatchOperationType & 1 << Constants.BATCH_OPERATION_WHITE_LIST) != 0) {
                            //                                sendToBlackWhiteList(mContactEntryAdapter.getSelectedContacts());
                        }
                       /* else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_LOCAL_CHAT_MEMBER) != 0) {
                            JSONArray jsonArray = new JSONArray();
                            mUsers = (HashMap<String, String>) mPreferenceUtil.getCloudContact(PreferenceUtil.CLOUD_PHONE_2_USEID);
                            if (mUsers == null) {
                                mUsers = new HashMap<String, String>();
                            }
                            for (int i = 0; i < mContactEntryAdapter.getSelectedContacts().size(); i++) {
                                ChatContact chatContact = mContactEntryAdapter.getSelectedContacts().get(i);
                                try {
                                    JSONObject jsonObject = new JSONObject();
                                    //                                        jsonObject.put("user_id", "316925");
                                    jsonObject.put("user_name", "");
                                    jsonObject.put("user_image", "");
                                    jsonObject.put("contact_id", 0);
//                                    if (mUsers.get(chatContact.getUserPhone()) != null) {
//                                        jsonObject.put("user_id", mUsers.get(PhoneNumberArea.formatPhoneNumDisplay(chatContact.getUserPhone())));
//                                    } else {
                                    jsonObject.put("user_id", "0");
//                                    }
                                    jsonArray.put(jsonObject);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            if (StringUtil.isEmpty(chatGroupId)) {
                                addChatGroupContactList(jsonArray);
                                mMemberCount = jsonArray.length() + 1 + "";
                            } else {
                                addMemberToChatGroup(jsonArray);
                            }
                            quitBatchOperation(true, true);
                        } */
                        else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_EVENT_ADD_LOCAL_RECEIVER) != 0) {
                            JSONArray jsonArray = new JSONArray();
                            mUsers = (HashMap<String, String>) mPreferenceUtil.getCloudContact(PreferenceUtil.CLOUD_PHONE_2_USEID);
                            if (mUsers == null) {
                                mUsers = new HashMap<String, String>();
                            }
                            if (eventReceiver != null && eventReceiver.length() > 0) {
                                try {
                                    JSONArray jsonArray1 = new JSONArray(eventReceiver);
                                    for (int i = 0; i < jsonArray1.length(); i++) {
                                        JSONObject jsonObject = jsonArray1.getJSONObject(i);
                                        jsonArray.put(jsonObject);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            for (int i = 0; i < mContactEntryAdapter.getSelectedContacts().size(); i++) {
                                ChatContact chatContact = mContactEntryAdapter.getSelectedContacts().get(i);
                                try {
                                    JSONObject jsonObject = new JSONObject();
                                    //                                        jsonObject.put("user_id", "316925");
                                    jsonObject.put("user_name", chatContact.getUserName());
                                    jsonObject.put("user_image", "");
                                    // if (mUsers.get(chatContact.getUserPhone()) != null) {
                                    //      jsonObject.put("user_id", mUsers.get(PhoneNumberArea.formatPhoneNumDisplay(chatContact.getUserPhone())));
                                    //  } else {
                                    jsonObject.put("user_id", "0");
                                    //  }
                                    boolean isSame = false;
                                    for (int j = 0; j < jsonArray.length(); j++) {
                                        if (jsonArray.getJSONObject(j).getString("user_id").equals(jsonObject.getString("user_id"))) {
                                            isSame = true;
                                            break;
                                        }
                                    }
                                    if (!isSame) {
                                        jsonArray.put(jsonObject);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            Intent intent = new Intent();
                            if (StringUtil.isEmpty(eventId)) {
                                if ("1".equals(((DialerApp) getApplication()).getmEventToWhere())) {
                                    intent.setClass(CloudDialerActivity.this, CreateNewEventActivity.class);
                                } else {
                                    intent.setClass(CloudDialerActivity.this, CustomEventActivity.class);
                                }
                                mEventData.setReceiver(jsonArray.toString());
                                mBundle.putSerializable("event_bundle", mEventData);
                                intent.putExtra("event_msg", mBundle);

                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                                mBatchOperationType = 0;
                            } else {
                                addReceiverToEvent(jsonArray.toString());
                            }

                        }
                    }

                    DialerApp app = (DialerApp) getApplication();
                    if (app.mYaoyiyaoShare) {
                        quitBatchOperation(true, true);
                        removeFullScreen();
                        app.mYaoyiyaoShare = false;
                        app.mYaoyiyaoShareContactId = -1L;
                    }
                }
                break;
                case Constants.UPDATE_AREA:
                    String text = (String) msg.obj;
                    /*String area = "";
                    if (text.length() > 3 && StringUtil.isNumeric(text)) {
                        PhoneNumberArea phoneNumberArea = PhoneNumberArea
                                .getInstance(CloudDialerActivity.this);
                        area = phoneNumberArea.getArea(text, true);
                    }*/

//                    if (mKeyboardOri == Constants.KEYBOARD_LAYOUT_VERTICAL) {
//                        mKeyboardVertFrag.setArea(area);
//                    } else if (mKeyboardOri == Constants.KEYBOARD_LAYOUT_HORIZONTAL) {
//                        mKeyboardHoriFrag.setArea(area);
//                    }
                    break;
                default:
                    break;
            }
        }
    }

    boolean usechange = true;

    public void changePage(boolean isBatch) {
        if (mListStatus == CloudDialerActivity.ListStatus.ENUM_SHOW_CONTACT_INFO || usechange == false) {
            return;
        }

        showDepartment = !showDepartment;

        if (showDepartment == false) {
            this.ivChange.setBackgroundResource(R.drawable.key_turn_selector);
            textChanged(null, 0);
        } else {
            this.ivChange.setBackgroundResource(R.drawable.key_search_selector);
        }

        if (isBatch == false) {
            keyBoardVert(true, null, showDepartment);
        } else {
            mLayoutSelectAll.setVisibility(View.VISIBLE);
            mShowModleChiceView.setAllToPressedState();
            keyBoardVert(true, "isbatch", showDepartment);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mainactvity_cancel:
                if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_CLOUD_UPLOAD) != 0 || (mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_GROUP_MEMBER) != 0) {
                    if (mBatchOperationType != 0) {
                        //showDepartment = true;
                        if (showDepartment == false) {
                            CloudDialerActivity.this.ivChange.setBackgroundResource(R.drawable.key_turn_selector);
                        } else {
                            CloudDialerActivity.this.ivChange.setBackgroundResource(R.drawable.key_search_selector);
                        }

                        mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;

                        if (changebundle != null) {
                            mCloudGid = Long.parseLong(changebundle.getString("group_id"));
                            groupId = changebundle.getString("group_id");
                            groupName = changebundle.getString("group_name");
                            mTreeFrag.clearContactList();
                            setFilterText("");
                            keyBoardVert(true, null, showDepartment);
                            return;
                        }
                        if ("cloud_contact_list".equals(mAction) == false) {
                            mBatchOperationType = 0;
                            finish();
                            return;
                        }

                        Intent intent = new Intent();
                        intent.putExtra(Constants.INTENT_TAG_ID, "0");
                        intent.putExtra(Constants.INTENT_TAG_NAME, "全部成员");
                        intent.putExtra("tag_count", "");
                        intent.putExtra("group_id", groupId);
                        intent.putExtra("group_name", groupName);
                        intent.putExtra("contact_id", contactId);
                        intent.setAction("structure_tag_click");
                        CloudDialerActivity.instance.ListRefresh(intent, Activity.RESULT_OK, null);
                        quitBatchOperation(true, true);
                        setFilterText("");
                        return;
                    }

                } else {
                    mBatchOperationType = 0;
                    finish();
                    return;
                }


                break;
            case R.id.ll_change:

                showDepartment = !showDepartment;

                if (showDepartment == false) {
                    this.ivChange.setBackgroundResource(R.drawable.key_turn_selector);
                } else {
                    this.ivChange.setBackgroundResource(R.drawable.key_search_selector);
                }

                keyBoardVert(true, null, showDepartment);

                break;
            case R.id.tv_back:
                setNoData(false); // 退出键盘界面时，无结果的提示消失
                mCurrentPage = 0;
                finish();
                break;
            case R.id.keyboard_title_ll_help:
                Intent intent = new Intent(CloudDialerActivity.this, WebViewActivity.class);
                intent.putExtra("title", "手机如何编辑组织架构?");
                intent.putExtra("type", 12);
                startActivity(intent);
                break;
            case R.id.select_all:
                boolean isChecked = mCbSelectAll.isChecked();
                mCbSelectAll.setChecked(!isChecked);
                if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_CLOUD_CHAT_MEMBER) != 0 && mCloudContactAdapter != null) {
                    mCloudContactAdapter.selectAllContactIds(!isChecked);
                } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_GROUP_MEMBER) != 0 && mCloudContactAdapter != null) {
                    mCloudContactAdapter.selectAllContactIds(!isChecked);
                } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_MANAGER_ADD) != 0 && mCloudContactAdapter != null) {
                    mCloudContactAdapter.selectAllContactIds(!isChecked);
                } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_MEMBER_DELETE) != 0 && mCloudContactAdapter != null) {
                    mCloudContactAdapter.selectAllContactIds(!isChecked);
                } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_EVENT_ADD_RECEIVER) != 0 && mCloudContactAdapter != null) {
                    mCloudContactAdapter.selectAllContactIds(!isChecked);
                } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_SCHEDULE_MANAGER) != 0 && mCloudContactAdapter != null) {
                    mCloudContactAdapter.selectAllContactIds(!isChecked);
                } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ATTENDANCE_MEMBER) != 0 && mCloudContactAdapter != null) {
                    mCloudContactAdapter.selectAllContactIds(!isChecked);
                } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_APPROVAL_LEADER) != 0 && mCloudContactAdapter != null) {
                    mCloudContactAdapter.selectAllContactIds(!isChecked);
                } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_WEEKLY_MANAGER) != 0 && mCloudContactAdapter != null) {
                    mCloudContactAdapter.selectAllContactIds(!isChecked);
                } else {
                    mSelectedListContactId = (ArrayList<Long>) mContactEntryAdapter
                            .getChangeContentId();
                    mContactEntryAdapter.selectAllContactIds(mSelectedListContactId, !isChecked);
                }
                sendMessageToHandler(Constants.FRESH_SEND_BUTTON_NUMBER);
                break;
            case R.id.mainactivity_btn_send:  // 键盘界面右上角完成键
                // 发送按钮，有两种不同的行为逻辑: 短信群发和发送名片
                    /*
                     * Message msg2 = mHandler.obtainMessage(); msg2.what =
                     * Constants.BATCH_OPERATION_MSG; mHandler.sendMessage(msg2);
                     */
                sendMessageToHandler(Constants.BATCH_OPERATION_MSG);
                setFilterText("");
                break;

            case R.id.dial_btn_dial:
            case R.id.dial_btn_h_dial:
                if (!mContactEntryAdapter.getIfCheckBoxShow()) {
                    String number = getFilterText();
//                    if (CommonCodeUtil.isDialable(number)) {
                    try {
                        if (TextUtils.isEmpty(number)) {
                            String s = CallLog.Calls.getLastOutgoingCall(mContext);
                            setFilterText(s);
                        } else {
//                            setFilterText("");
                            CommonCodeUtil.launchCallByNumber(this, number);
                        }
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(this, getString(R.string.activity_not_found),
                                Toast.LENGTH_LONG).show();
                    }
//                    }
                }
                break;
            case R.id.dial_btn_send_msg:
            case R.id.dial_btn_h_send_msg:
                if (!mContactEntryAdapter.getIfCheckBoxShow() && !mIfBatchOperation) {
                    String number = getFilterText();
                    if (number.equals("")) {
                        /*
                         * String s; s = Calls.getLastOutgoingCall(mContext);
                         * setFilterText(s);
                         */
                        CommonCodeUtil.launchSendMessage(this, "", null);
                    } else if (number.length() > 0) {
                        PhoneNumberArea phoneNumberArea = PhoneNumberArea
                                .getInstance(CloudDialerActivity.this);
                        number = phoneNumberArea.replaceIpCall(number);
//                        setFilterText("");
                        CommonCodeUtil.launchSendMessage(this, number, null);
                    }
                } else if (mIfBatchOperation) {
                    // sendMessageToHandler(Constants.BATCH_OPERATION_MSG);
                } else {

                }
                break;
            case R.id.slip_key:
                mHelpSlipKey.setVisibility(View.GONE);
                mPreferenceUtil.save("slip_key_v1", false);
                break;
            case R.id.structure_add:
                mHelpStructureAdd.setVisibility(View.GONE);
                mPreferenceUtil.save("structure_add_v1", false);
                break;
            case R.id.structure_edit:
                mHelpStructureEdit.setVisibility(View.GONE);
                mPreferenceUtil.save("structure_edit_v1", false);
                break;
            default:
                break;
        }
    }

    /**
     * 播放皮肤声音
     */
    public void playPhone(Mp3Player player, final AssetFileDescriptor afd, String id, String filePath) {

        if (player == null) {
            player = new Mp3Player(mContext);
        }

        if (mIsHaveTone > 0) {
            AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
            int ringerMode = audioManager.getRingerMode();
            if ((ringerMode == AudioManager.RINGER_MODE_SILENT)
                    || (ringerMode == AudioManager.RINGER_MODE_VIBRATE)) {
                return;
            }
            player.setSource(id, afd, filePath);
        }
    }

    public void setFilterText(String text) {

        Log.d("textChanged_search", "  setFilterText  ======= " + text);

        if (mKeyboardOri == Constants.KEYBOARD_LAYOUT_HORIZONTAL) {
            mKeyboardHoriFrag.setFilterText(text);
        } else {
            mKeyboardVertFrag.setFilterText(text);
        }
    }

    /**
     * 检查手机SIM卡
     *
     * @return
     */
    public boolean checkSIMCard() {
        TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
        if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
            return true;
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        mCurrentPage = 0;
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_CLOUD_UPLOAD) != 0 || (mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_GROUP_MEMBER) != 0) {
                    if (mBatchOperationType != 0) {
                        //showDepartment = true;
                        if (showDepartment == false) {
                            CloudDialerActivity.this.ivChange.setBackgroundResource(R.drawable.key_turn_selector);
                        } else {
                            CloudDialerActivity.this.ivChange.setBackgroundResource(R.drawable.key_search_selector);
                        }

                        mListStatus = ListStatus.ENUM_SHOW_CLOUD_CONTACT;

                        if (changebundle != null) {
                            mCloudGid = Long.parseLong(changebundle.getString("group_id"));
                            groupId = changebundle.getString("group_id");
                            groupName = changebundle.getString("group_name");
                            mTreeFrag.clearContactList();
                            setFilterText("");
                            keyBoardVert(true, null, showDepartment);
                            return true;
                        }
                        if ("cloud_contact_list".equals(mAction) == false) {
                            mBatchOperationType = 0;
                            finish();
                            return true;
                        }

                        Intent intent = new Intent();
                        intent.putExtra(Constants.INTENT_TAG_ID, "0");
                        intent.putExtra(Constants.INTENT_TAG_NAME, "全部成员");
                        intent.putExtra("tag_count", "");
                        intent.putExtra("group_id", groupId);
                        intent.putExtra("group_name", groupName);
                        intent.putExtra("contact_id", contactId);
                        intent.setAction("structure_tag_click");
                        CloudDialerActivity.instance.ListRefresh(intent, Activity.RESULT_OK, null);
                        quitBatchOperation(true, true);
                        setFilterText("");
                        return true;
                    }

                } else {
                    mBatchOperationType = 0;
                    finish();
                    return true;
                }

                break;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 批处理时现实全部和已选状态变化的监听
     */
    class MyOnChoiceChangeListener implements TwiceTextChoiceView.OnChoiceChangeListener {

        @Override
        public void choiceAll() {
            mLayoutSelectAll.setVisibility(View.VISIBLE);
            if (mListStatus == ListStatus.ENUM_SHOW_CONTACT_INFO) {
                mContactEntryAdapter.changeToAllContent();
            } else {
                mCloudContactAdapter.changeToAllContent();
            }

            mKeyboardVertFrag.enableInput(true);
        }

        @Override
        public void choiceSelected() {
            mLayoutSelectAll.setVisibility(View.GONE);
            if (mListStatus == ListStatus.ENUM_SHOW_CONTACT_INFO) {
                mContactEntryAdapter.changeSelectedContent();
            } else {
                mCloudContactAdapter.changeSelectedContent();
            }

            mKeyboardVertFrag.enableInput(false);
        }
    }

    public void appendCloudContactListReq() {
        if (mListStatus != ListStatus.ENUM_SHOW_CLOUD_CONTACT)
            return;

        if (!mLoading) {
            setNoData(false);
            mLoading = true;
            String searchText = getFilterText();
            if (TextUtils.isEmpty(searchText)) {
                getCloudContactList(String.valueOf(mCloudGid), mCurrentPage + 1,
                        mCloudHandler.obtainMessage(MSG_CONTACT_APPEND_LIST), tagId, contactId);
            } else {
                sendPys(searchText, mCloudGid, AsynHttpClient.DEFAULT_PAGE_SIZE, mCurrentPage + 1,
                        mCloudHandler.obtainMessage(MSG_CONTACT_APPEND_LIST), tagId);
            }
        }
    }


    public void ListRefresh(Intent data, int resultCode, ElementData element) {
        if (data != null) {
            String mAction = data.getAction();
            //mContactsListView.setAdapter(null);
            if (resultCode == RESULT_OK) {
                quitBatchOperation(true, true);
                //freshContactsByStatus();
                tagId = this.tagId;

                if (data.getStringExtra(Constants.INTENT_TAG_ID) != null) {
                    tagId = data.getStringExtra(Constants.INTENT_TAG_ID);
                }
                if (!tagId.equals("0")) {
                    if (element != null && element.contactList != null) {
                        if (mIfBatchOperation) {
                            mShowModleChiceView.backToDefaultState();
//                            if (mCloudContactAdapter.mIsShowSelected) {
                            mCloudContactAdapter.changeToAllContent();
//                            }
                        }
                        updateCloudContactList(element.contactList);
                    } else {
                        getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
                    }
                } else {

                   /* if (this.rootcontactList == null) {

                        getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);

                    } else {*/
                    updateCloudContactList(rootcontactList);

                  /*  }*/
                }
            } else if (resultCode == -2) {
                //quitBatchOperation(true, true);
                //freshContactsByStatus();
                mLayoutSelectAll.setVisibility(View.VISIBLE);
                mShowModleChiceView.setAllToPressedState();


                if (data.getStringExtra(Constants.INTENT_TAG_ID) != null) {
                    tagId = data.getStringExtra(Constants.INTENT_TAG_ID);
                }
                if (data.getStringExtra(Constants.INTENT_TAG_NAME) != null) {
                    tagName = data.getStringExtra(Constants.INTENT_TAG_NAME);
                }
                tagCount = data.getStringExtra("tag_count");
                groupId = data.getStringExtra("group_id");
                groupName = data.getStringExtra("group_name");
                clickPosition = data.getIntegerArrayListExtra("clickPosition");
                currentPosition = data.getIntExtra("currentPosition", 0);
                contactCount = data.getIntExtra("contact_count", 0);
                if (!tagId.equals("0")) {

                    if (element != null && element.contactList != null) {
                        if (mIfBatchOperation) {
                            mShowModleChiceView.backToDefaultState();
//                            if (mCloudContactAdapter.mIsShowSelected) {
                            mCloudContactAdapter.changeToAllContent();
//                            }
                        }
                        updateCloudContactList(element.contactList);
                    } else {
                        if (!StringUtil.isEmpty(groupId)) {
                            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
                        }
                    }
                } else {
                    if (this.rootcontactList == null) {
                        getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);

                    } else {
                        updateCloudContactList(rootcontactList);
                    }
                }
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
          /*  case REQ_DOWNLOAD_SKIN:
                //            refreshSkinList();
                if (mSkinListAdapter != null) {
                    mSkinListAdapter.setData(getSkinData());
                }
                break;*/
            case Constants.ACTIVITY_REQUEST_DISPLAYCOMMUNICATION: // 详情操作返回
                mIsLoad = false;
                freshCloudContactFromResult(resultCode);

                if (data == null) {
                    return;
                }
                if (resultCode == Constants.ACTIVITY_RESULT_DISPLAYCOMMUNICATION_DELETE) {

                    final String mContactName = data.getStringExtra(Constants.CONTACT_NAME_KEY);
                    final long mContactID = data.getLongExtra(Constants.CONTACT_ID_KEY, 0);
                    ContactsDBReader.removeContactByContactId(getContentResolver(),
                            mContactID);
                    if (mPinyinSearch != null) {
                        mPinyinSearch.delPinyinDict(mContactName, mContactID);
                    }
                    mPreferenceUtil.delObject(Long.toString(mContactID));
                    mPreferenceUtil.delete(PreferenceUtil.NAMECARD_CONTACTID);

                    runOnUiThread(new Runnable() {
                        public void run() {
                            //                                     freshAllResult();
                            String filterText = getFilterText();
                            if (TextUtils.isEmpty(filterText)) {
                                freshContactsByStatus();
                            } else {
                                freshSearchDisplay();
                            }
                        }
                    });

                    new Thread() {
                        public void run() {
                            refreshNumber();
                        }
                    }.start();


                    /*final String mContactName = data.getStringExtra(Constants.CONTACT_NAME_KEY);
                    final long mContactID = data.getLongExtra(Constants.CONTACT_ID_KEY, 0);
                    String confirmToDel = getString(R.string.dialog_label_confirm_note);
                    String delMsg = getString(R.string.delete_contact,
                            mContactName);
                    String confirmBtn = getString(R.string.ok);
                    String cancelBtn = getString(R.string.cancel);
                    AllDialogUtil dialogUtil = AllDialogUtil
                            .getInstance(CloudDialerActivity.this);
                    dialogUtil.titleMsgBtnStyle(confirmToDel, delMsg, confirmBtn, cancelBtn);
                    dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

                        @Override
                        public void onConfirmClick(Dialog lDialog) {

                            ContactsDBReader.removeContactByContactId(getContentResolver(),
                                    mContactID);
                            if (mPinyinSearch != null) {
                                mPinyinSearch.delPinyinDict(mContactName, mContactID);
                            }
                            mPreferenceUtil.delObject(Long.toString(mContactID));
                            mPreferenceUtil.delete(PreferenceUtil.NAMECARD_CONTACTID);

                            runOnUiThread(new Runnable() {
                                public void run() {
                                    //                                     freshAllResult();
                                    String filterText = getFilterText();
                                    if (TextUtils.isEmpty(filterText)) {
                                        freshContactsByStatus();
                                    } else {
                                        freshSearchDisplay();
                                    }
                                }
                            });

                            lDialog.dismiss();
                            new Thread() {
                                public void run() {
                                    refreshNumber();
                                }
                            }.start();

                        }

                        @Override
                        public void onCancelClick(Dialog lDialog) {
                            lDialog.dismiss();
                        }
                    });*/
                }
                break;
        }
    }

    /**
     * 如果搜索框内有数据，刷新列表
     */
    public void freshSearchDisplay() {
        String filterText = getFilterText();
        if (TextUtils.isEmpty(filterText))
            return;
        // switch between T9 and all-words

        if (mListStatus == ListStatus.ENUM_SHOW_CLOUD_CONTACT) {
            // if mDisplayCallLog == true it will set to call log mode below
            freshCloudContact();
            return;
        }

        if (filterText != null && filterText.length() > 0) {
            mContactEntryAdapter.setCurrentSearchText(filterText);
            if (mListManager != null) {
                mListManager.onRefresh(filterText, mIfShowPeopleNoPhone);
            }
        }
        mContactEntryAdapter.setCurrentSearchText(filterText);
        freshContactsByStatus();
    }

    /**
     * 刷新云端分组数据
     */
    public void freshCloudContact() {
        if (selectedGroup != null) {
            if (selectedGroup.groupType == 1) {
                setAddContactAble(true);
            } else {
                setAddContactAble(false);
            }
        } else {
            setAddContactAble(false);
        }
        String searchText = getFilterText();
        mCloudHandler.post(new Runnable() {
            @Override
            public void run() {
                setNoData(false);
            }
        });

        if (TextUtils.isEmpty(searchText)) {
            getCloudContactList(String.valueOf(mCloudGid), mCurrentPage,
                    mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
        } else {
            sendPys(searchText, mCloudGid, AsynHttpClient.DEFAULT_PAGE_SIZE, mCurrentPage,
                    mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId);
        }
    }


    public void refreshNumber() {
        ContactsDBReader.resetAllContactsNumber(CloudDialerActivity.this);
    }


    public void appendCloudContactList(ArrayList<CloudContact> contactList) {
        mCloudContactAdapter.appendData(contactList);
    }

    public void getCloudContactList(String gid, int pageIndex, Message callback, String tagId, String contactId) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (!StringUtil.isEmpty(tagId) && !"-1".equals(tagId) && !mIsAddGroupMember) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TAG_ID, tagId));
        } else {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TAG_ID, "0"));
        }

        if (groupName != null) {
            mTvListName.setText(groupName);
        }
        //mCloudContactAdapter.setSection("云通讯录 (" + tagCount + ")");
        //mCloudContactAdapter.setSection(tagName);
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, gid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CURRENT_CONTACT_ID, contactId));
//        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGE_INDEX, String.valueOf(pageIndex)));
//        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGE_SIZE,
//                AsynHttpClient.DEFAULT_PAGE_SIZE));

        GetContactListMsg getContactList = new GetContactListMsg(callback);
        getContactList.type = CLOUD_SEARCH_MSG;
        getContactList.mApi = AsynHttpClient.API_CONTACT_GETLIST;
        getContactList.mParams = nvps;
        AsynHttpClient.getInstance(this).execCcHttp(getContactList);
    }


    class CloudCompartor implements Comparator<CloudContact> {
        @Override
        public int compare(CloudContact o1, CloudContact o2) {
            CloudContact contactId1 = (CloudContact) o1;
            CloudContact contactId2 = (CloudContact) o2;

            if (!contactId1.userId.equals("0") && contactId2.userId.equals("0")) {
                return -1;
            } else if (contactId1.userId.equals("0") && !contactId2.userId.equals("0")) {
                return 1;
            }


            String nameValue1 = contactId1.contactName;
            String nameValue2 = contactId2.contactName;

            java.util.Comparator cmp = java.text.Collator.getInstance(java.util.Locale.CHINA);
            return cmp.compare(nameValue1, nameValue2);
            //return nameValue2.compareTo(nameValue1);

        }
    }


    /**
     * 更新云端联系人数据
     *
     * @param contactList
     */
    public void updateCloudContactList(ArrayList<CloudContact> contactList) {

        if (contactList != null) {
            CloudCompartor mc = new CloudCompartor();
            Collections.sort(contactList, mc);
        }

        if (selectedGroup == null){
            selectedGroup = new CloudGroup();
            selectedGroup.groupId = 0;
            selectedGroup.groupName = "企业";
            selectedGroup.contactCount = 10;
        }

        if (mCloudContactAdapter == null && selectedGroup != null) {
            mCloudContactAdapter = new CloudContactAdapter(this, selectedGroup, contactList, imageLoader);
            mCloudContactAdapter.setColor(mSkinCommon.nameColor, mSkinCommon.jobTitleColor, mSkinCommon.phoneColor,
                    mSkinCommon.listTextHightLightColor, mSkinCommon.listSectionColor, mSkinCommon.barTitleColor);
            mCloudContactAdapter.setInterrupted(false);
        } else {
            if (selectedGroup != null) {
                mCloudContactAdapter.setInterrupted(false);
                mCloudContactAdapter.updateCloudGroup(selectedGroup);
                mCloudContactAdapter.updateData(contactList, getFilterText().contains("*"));
            } else {
//                Toast.makeText(this, R.string.err_fresh_cloud_contact, Toast.LENGTH_LONG).show();
            }
        }

        if (contactList != null) {

            if (contactList.size() == 0) {
                setNoData(true);
            } else {
                setNoData(false);
            }
        }
        mContactsListView.setAdapter(mCloudContactAdapter);
    }

    private void freshCloudContactFromResult(int resultCode) {
        if (mListStatus == ListStatus.ENUM_SHOW_CLOUD_CONTACT) {
            // mCloudContactAdapter.clearSelectedStatus();
        }
        if (resultCode == Constants.ACTIVITY_RESULT_CLOUD_CONTACT_DELETE) {
            freshCloudContact();
        }
    }

    public String getFilterText() {
        String filterText = null;
        if (mKeyboardOri == Constants.KEYBOARD_LAYOUT_HORIZONTAL) {
            filterText = mKeyboardHoriFrag.getFilterText();
        } else {
            filterText = mKeyboardVertFrag.getFilterText();
        }

        filterText = CloudGroupListCenter.searchReplace(filterText);

        return filterText;
    }


    public static void setBgAndScalType(ImageButton ib, SkinCommonData skin) {
        ib.setScaleType(skin.scaleType);
        ib.setBackgroundColor(skin.backgroundColor);
    }

    private PopupWindow mAddContactsWin;

    /**
     * 属键盘加号键弹窗
     *
     * @param isInCloud
     */
    public void showPlusButtonWindow(final boolean isInCloud) {
        if (isInCloud) {
            if (groupType != 1 && "1".equals(userType)) {//不允许成员添加人
                Toast.makeText(CloudDialerActivity.this, "对不起，该号码簿不允许成员添加新人", Toast.LENGTH_LONG).show();
            } else if (groupId.equals("561")) {
                Toast.makeText(CloudDialerActivity.this, "对不起，该号码簿不允许成员添加新人", Toast.LENGTH_LONG).show();
            } else {
                View mainView = mLayoutInflater.inflate(R.layout.alert_dialog_menu_layout, null);
                if (isInCloud) {
                    View upload_view = mainView.findViewById(R.id.btn_add_contacts_by_upload);
                    TextView text_create = (TextView) mainView.findViewById(R.id.text_create);
                    text_create.setText("添加新成员");
                    upload_view.setVisibility(View.VISIBLE);
                }
                mAddContactsWin = new PopupWindow(this);
                mAddContactsWin.setBackgroundDrawable(new BitmapDrawable());
                mAddContactsWin.setFocusable(true);
                mAddContactsWin.setTouchable(true);
                mAddContactsWin.setOutsideTouchable(true); // 设置非PopupWindow区域可触摸
                mAddContactsWin.setContentView(mainView);
                mAddContactsWin.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                mAddContactsWin.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                mAddContactsWin.setAnimationStyle(R.style.bottomStyle);
                //从本地上传
                ((Button) mainView.findViewById(R.id.btn_add_contacts_by_upload)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //mKeyboardVertFrag.mDigits_words_vertical.setText("");
                        mAddContactsWin.dismiss();
                        mListStatus = ListStatus.ENUM_SHOW_CONTACT_INFO;
                        freshContactsByStatus();
                        //                getDmg().setSelect(1, true);
                        batchOperation(Constants.BATCH_OPERATION_CLOUD_UPLOAD);
                        setNoData(false);
                    }
                });
                //手工添加
                ((Button) mainView.findViewById(R.id.btn_add_contacts_by_manual))
                        .setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                mAddContactsWin.dismiss();
                                setNoData(false);
                                Intent insert = new Intent(CloudDialerActivity.this, AddContactByHandActivity.class);
                                insert.putExtra("group_id", "" + mCloudGid);
                                insert.putExtra("tag_id", tagId);
                                insert.putExtra(CloudGroup.class.getName(), selectedGroup);
                                startActivity(insert);
                            }
                        });

                ((Button) mainView.findViewById(R.id.btn_cancel)).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        mAddContactsWin.dismiss();
                    }
                });
                mAddContactsWin.showAtLocation(mainView, Gravity.BOTTOM, 0, 0);
                mAddContactsWin.update();

                mainView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        mAddContactsWin.dismiss();
                        return false;
                    }
                });
            }
        }
    }

    private void updateSelectTitleSkin() {
        View.OnTouchListener leftListener = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (v.isSelected()) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        v.setBackgroundDrawable(mSkinCommon.left[1]);
                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
                        v.setBackgroundDrawable(mSkinCommon.left[0]);
                    }
                } else {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        v.setBackgroundDrawable(mSkinCommon.left[0]);
                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
                        v.setBackgroundDrawable(mSkinCommon.left[1]);
                    }
                }
                return false;
            }
        };
        View.OnTouchListener rightListener = new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (v.isSelected()) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        v.setBackgroundDrawable(mSkinCommon.right[1]);
                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
                        v.setBackgroundDrawable(mSkinCommon.right[0]);
                    }
                } else {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        v.setBackgroundDrawable(mSkinCommon.right[1]);
                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
                        v.setBackgroundDrawable(mSkinCommon.right[0]);
                    }
                }
                return false;
            }
        };
        //mTabContactGroup.setBackgroundDrawable(mSkinCommon.right[0]);
        //mTabContactGroup.setOnTouchListener(rightListener);
        //mTabSelectAll.setBackgroundDrawable(mSkinCommon.left[1]);
        //mTabSelectAll.setOnTouchListener(leftListener);

        float[] outerR = new float[]{
                12, 12, 12, 12, 12, 12, 12, 12
        };
        RoundRectShape rr = new RoundRectShape(outerR, null, null);
        final ShapeDrawable sd = new ShapeDrawable(rr);
        sd.getPaint().setColor(mSkinCommon.tintColor);

        View.OnTouchListener selector = new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                if (action == MotionEvent.ACTION_DOWN) {

                    ((TextImageButton) v).setImageResource(R.drawable.navigation_btn_pressed);

                } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {

                    ((TextImageButton) v).setImageResource(R.drawable.navigation_btn_normal);
                }
                return false;
            }
        };
        //mBtnCancel.setBackgroundDrawable(sd);
        //mBtnCancel.setImageResource(R.drawable.navigation_btn_normal);
        //mBtnCancel.setOnTouchListener(selector);
        //mBtnSend.setBackgroundDrawable(sd);
        //mBtnSend.setImageResource(R.drawable.navigation_btn_normal);
        //mBtnSend.setOnTouchListener(selector);
    }

    private ArrayList<SkinDirData> getSkinData() {
        GetSkinResource gr = new GetSkinResource(CloudDialerActivity.this);
        return gr.getSkinDir(CloudDialerActivity.this);
    }

    public void sendMessageToHandler(int messageType) {
        Message msg2 = mHandler.obtainMessage();
        msg2.what = messageType;
        mHandler.sendMessage(msg2);
    }

    /**
     * 临时处理，待修改
     *
     * @return
     */
    public int getListFlag() {
        return mListManager.getListFlag();
    }

    public void afterQueryComplete() {
        if (LocalLogin.getInstance().isLogedin()) {
//                    freshCloudUserList();
            mPreferenceUtil.registerCloudContactListener(this);
        }
    }

    public void setSelectImage(boolean onOroff) {
        mCbSelectAll.setChecked(onOroff);
    }

    public boolean getIsDisplayUnderPanel() {
        return mIsDisplayUnderPanel;
    }


    class MyCompartor implements Comparator<Long> {
        @Override
        public int compare(Long o1, Long o2) {
            Long contactId1 = (Long) o1;
            Long contactId2 = (Long) o2;


            Person person1 = mPreferenceUtil.getPerson(contactId1 + "");
            Person person2 = mPreferenceUtil.getPerson(contactId2 + "");

            if (person1 == null || person2 == null) {
                return 0;
            }


            String registPhone1 = null;
            String registPhone2 = null;

            if (mCloudUser != null) {
                registPhone1 = mCloudUser.get(contactId1);
                registPhone2 = mCloudUser.get(contactId2);
            }

            if (registPhone1 == null && registPhone2 != null) {
                return 1;
            } else if (registPhone1 != null && registPhone2 == null) {
                return -1;
            } else if (registPhone1 == null && registPhone2 == null) {
                return -2;
            }

            String nameValue1 = person1.getDisplayName();
            String nameValue2 = person2.getDisplayName();
            if (nameValue1 == null || nameValue2 == null) {
                return -3;
            }
            java.util.Comparator cmp = java.text.Collator.getInstance(java.util.Locale.CHINA);
            return cmp.compare(nameValue1, nameValue2);

//	           return nameValue2.compareTo(nameValue1);

        }
    }

    // add background query, search all contacts
    private final class BackgroundQueryHandler extends AsyncQueryHandler {


        public BackgroundQueryHandler(ContentResolver cr) {
            super(cr);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, final Cursor cursor) {
            if (mFirstQuery) {
                afterQueryComplete();

                mFirstQuery = false;
            }

            if (cursor == null)
                return;

            int contactedPeople = 0;

            if (Constants.IS_START_UP) {
                startUp(cursor);
            } else {
                mAllContactId.clear();
                if (ContactsDBReader.mGroupList == null) {
                    ContactsDBReader.resetAllContactsNumber(mContext);
                }
                try {
                    cursor.moveToPosition(-1);
                    while (cursor.moveToNext()) {

                        long contactId = cursor.getLong(ContactsDBReader.SUMMARY_ID_COLUMN_INDEX);
                        mAllContactId.add(contactId);
                        int contactedNumber = cursor
                                .getInt(ContactsDBReader.SUMMARY_TIMES_CONTACTED_COLUMN_INDEX);
                        if (contactedNumber > 0) {
                            contactedPeople++;
                        }
                    }
                    mSelectedListContactId = mAllContactId;

                    if (mSelectedListContactId.size() == 0) {
                        mNull.setVisibility(View.VISIBLE);
                    } else {
                        mNull.setVisibility(View.GONE);
                    }


                } finally {
                    cursor.close();
                }

                if (LocalLogin.getInstance().isLogedin()) {
                    if (mCloudUser == null || mCloudUser.size() == 0) {
                        mCloudUser = (HashMap<Long, String>) mPreferenceUtil.getCloudContact(PreferenceUtil.CLOUD_REGIST_USER);

                        if (mCloudUser == null) {
                            mCloudUser = new HashMap<Long, String>();
                            // 防止本地通信录崩溃
                            mCloudUser.put(0L, "0");
                        }
                    }
                }

                MyCompartor mc = new MyCompartor();
                Collections.sort(mAllContactId, mc);


                Pair<String, List<Long>> sectionPair = null;// new Pair<String,
                // List<Long>>("按姓名排序",
                // mAllContactId);
                List<Pair<String, List<Long>>> res = new ArrayList<Pair<String, List<Long>>>();
                mSortByProperty = Constants.ORDER_BY_NAME_INDEX;
                if (mSortByProperty == Constants.ORDER_BY_NAME_INDEX) {
                    String title = getSections()[0] + "(" + mAllContactId.size() + ")";
                    sectionPair = new Pair<String, List<Long>>(title, mAllContactId);
                    res.add(sectionPair);
                }
                /*
                else if (mSortByProperty == Constants.ORDER_BY_CALL_LOG_INDEX)
                {
                    if (contactedPeople > 0)
                    {
                        String title = getSections()[0] + "(" + contactedPeople + ")";
                        sectionPair = new Pair<String, List<Long>>(title, mAllContactId.subList(0,
                                contactedPeople));
                        res.add(sectionPair);

                        title = getSections()[1] + "(" + (mAllContactId.size() - contactedPeople) + ")";
                        sectionPair = new Pair<String, List<Long>>(title, mAllContactId.subList(
                                contactedPeople, mAllContactId.size()));
                        res.add(sectionPair);
                    }
                    else
                    {
                        String title = getSections()[1] + "(" + mAllContactId.size() + ")";
                        sectionPair = new Pair<String, List<Long>>(title, mAllContactId);
                        res.add(sectionPair);
                    }
                }
                */

/*
                @SuppressWarnings("unchecked")
                final HashMap<Long, Integer> contactId2DistStatus = (HashMap<Long, Integer>) mPreferenceUtil
                        .getCloudContact(PreferenceUtil.CONTACT_ID_2_DIST_STATUS);

                // 获取已注册的号码，此处获取不到，有问题
                HashMap<Long, String> registUsers = (HashMap<Long, String>) mPreferenceUtil.getObject(PreferenceUtil.CLOUD_REGIST_USER);
*/
                //               if (mListStatus == ListStatus.ENUM_SHOW_BATCH_OPERATION) {
//                    mContactEntryAdapter.changeContent(res);
//                    mContactsListView.setAdapter(mContactEntryAdapter);
//                    mContactEntryAdapter.notifyDataSetChanged();
//                } else if (mListStatus != ListStatus.ENUM_SHOW_CALL_LOG) {


                mContactEntryAdapter.changeContent(res);


                mContactEntryAdapter.notifyDataSetChanged();
//                    mContactEntryAdapter.setCloudUserData(contactId2DistStatus);
                //mContactEntryAdapter.setCloudUser(registUsers);
                //mContactsListView.setPinnedHeaderView(mLayoutInflater.inflate(
                //R.layout.item_composer_header, mContactsListView, false));
                mContactsListView.setAdapter(mContactEntryAdapter);
            }
//
//                }

            String filterText = getFilterText();
            if (!TextUtils.isEmpty(filterText)) {
//                                if (mGroupID == null
//                                        || mGroupID == GroupOperationActivity.DISPLAY_GROUP_BUTTON_ALLCONTACTS) {
//                                    mListManager.setListFlag(Constants.SHOW_CONTACT_INFO);
//                                } else {
//                                    mListManager.setListFlag(Constants.SHOW_GROUP_INFO);
//                                }
                mContactEntryAdapter.setCurrentSearchText(filterText);
                if (mListManager != null) {
                    mListManager.onRefresh(filterText, mIfShowPeopleNoPhone);
                }
            }
            //           }


        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {

        }

    }

    public String[] getSections() {
        if (mSortByProperty == Constants.ORDER_BY_NAME_INDEX) {
            return Constants.ORDER_BY_NAME;
        } else {
            return Constants.ORDER_BY_CALL_LOG;
        }
    }

    /**
     * 初始化 Manager
     *
     * @param intent
     */
    private void initListManager(Intent intent) {
        List<Pair<String, List<Long>>> contactIds = new ArrayList<Pair<String, List<Long>>>();
        mContactEntryAdapter = new ContactEntryAdapter(mLayoutInflater, this, contactIds);

        // mContactPhoneEntryAdapter = new
        // ContactPhoneEntryAdapter(mLayoutInflater, this, contactIds);
        // 将发送 Button 赋值给适配器
        // mContactsListAdapter.setmDialContactsActivitSendBtn(mBtnSend);

        //        mMainLayout.setClipChildren(false);
        if (mListManager == null) {
            mListManager = new ResultListManager(this, mContactsListView, mShowContent);
        }
        freshContactsByStatus();
        // result list需要和adapter关联
        // mContactsListAdapter.setResultList(mListManager.getResultList());
        // mContactsListView.setAdapter(mContactsListAdapter);
        mContactsListView.setAdapter(mContactEntryAdapter);
        mContactsListView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mListDownY = event.getY();
                        break;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        mListDownY = 0.f;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        // no special means of 16
                        if (Math.abs(event.getY() - mListDownY) > 16
                            //: vert keyboard
                            // && View.VISIBLE == mT9_h.getVisibility()
                                ) {
                            //                            setKeypadInVisible();
                        }
                        break;
                }
                return false;
            }
        });
    }

    public void startUp(final Cursor cursor) {
        if (!whileLock) {
            whileLock = true;
            new AsyncTask<Void, Void, ArrayList<Long>>() {

                @Override
                protected ArrayList<Long> doInBackground(Void... params) {
                    contactedPeople = 0;
                    mAllContactId.clear();
                    //                    if (ContactsDBReader.mGroupList == null) {
                    ContactsDBReader.resetAllContactsNumber(mContext);
                    //                    }
                    try {
                        cursor.moveToPosition(-1);
                        while (cursor.moveToNext()) {

                            long contactId = cursor.getLong(ContactsDBReader.SUMMARY_ID_COLUMN_INDEX);
                            mAllContactId.add(contactId);
                            int contactedNumber = cursor
                                    .getInt(ContactsDBReader.SUMMARY_TIMES_CONTACTED_COLUMN_INDEX);
                            if (contactedNumber > 0) {
                                contactedPeople++;
                            }
                        }
                        mSelectedListContactId = mAllContactId;

                    } finally {
                        cursor.close();
                    }

                    return mAllContactId;
                }


                @Override
                protected void onPostExecute(ArrayList<Long> longs) {
                    if (longs != null) {
                        if (longs.size() == 0) {
                            mNull.setVisibility(View.VISIBLE);
                        } else {
                            mNull.setVisibility(View.GONE);
                        }


                        if (LocalLogin.getInstance().isLogedin()) {
                            if (mCloudUser == null || mCloudUser.size() == 0) {
                                mCloudUser = (HashMap<Long, String>) mPreferenceUtil.getCloudContact(PreferenceUtil.CLOUD_REGIST_USER);

                                if (mCloudUser == null) {
                                    mCloudUser = new HashMap<Long, String>();
                                    // 防止本地通信录崩溃
                                    mCloudUser.put(0L, "0");
                                }
                            }
                        }

                        MyCompartor mc = new MyCompartor();
                        Collections.sort(longs, mc);


                        Pair<String, List<Long>> sectionPair = null;// new Pair<String,
                        // List<Long>>("按姓名排序",
                        // mAllContactId);
                        List<Pair<String, List<Long>>> res = new ArrayList<Pair<String, List<Long>>>();
                        mSortByProperty = Constants.ORDER_BY_NAME_INDEX;
                        if (mSortByProperty == Constants.ORDER_BY_NAME_INDEX) {
                            String title = getSections()[0] + "(" + longs.size() + ")";
                            sectionPair = new Pair<String, List<Long>>(title, longs);
                            res.add(sectionPair);
                        } else if (mSortByProperty == Constants.ORDER_BY_CALL_LOG_INDEX) {
                            if (contactedPeople > 0) {
                                try {
                                    String title = getSections()[0] + "(" + contactedPeople + ")";
                                    sectionPair = new Pair<String, List<Long>>(title, longs.subList(0,
                                            contactedPeople));
                                    res.add(sectionPair);

                                    title = getSections()[1] + "(" + (longs.size() - contactedPeople) + ")";
                                    sectionPair = new Pair<String, List<Long>>(title, longs.subList(
                                            contactedPeople, longs.size()));
                                    res.add(sectionPair);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    whileLock = false;
                                    Constants.IS_START_UP = false;
                                    return;
                                }

                            } else {
                                String title = getSections()[1] + "(" + longs.size() + ")";
                                sectionPair = new Pair<String, List<Long>>(title, longs);
                                res.add(sectionPair);
                            }
                        }

                        @SuppressWarnings("unchecked")
                        final HashMap<Long, Integer> contactId2DistStatus = (HashMap<Long, Integer>) mPreferenceUtil
                                .getCloudContact(PreferenceUtil.CONTACT_ID_2_DIST_STATUS);
                        // 获取已注册的号码，此处获取不到，有问题
                        HashMap<Long, String> registUsers = (HashMap<Long, String>) mPreferenceUtil.getCloudContact(PreferenceUtil.CLOUD_REGIST_USER);

                        mContactEntryAdapter.changeContent(res);
                        mContactEntryAdapter.setCloudUser(registUsers);
                        //mContactsListView.setPinnedHeaderView(mLayoutInflater.inflate(
                        //R.layout.item_composer_header, mContactsListView, false));
                        mContactsListView.setAdapter(mContactEntryAdapter);
                        mContactEntryAdapter.notifyDataSetChanged();
//                        if (mListStatus == ListStatus.ENUM_SHOW_BATCH_OPERATION) {
//                            mContactEntryAdapter.changeContent(res);
//                            mContactsListView.setAdapter(mContactEntryAdapter);
//                            mContactEntryAdapter.notifyDataSetChanged();
//                        } else if (mListStatus != ListStatus.ENUM_SHOW_CALL_LOG) {
//                            mContactEntryAdapter.changeContent(res);
////                            mContactEntryAdapter.setCloudUserData(contactId2DistStatus);
//                            mContactEntryAdapter.setCloudUser(registUsers);
//                            mContactsListView.setPinnedHeaderView(mLayoutInflater.inflate(
//                                    R.layout.item_composer_header, mContactsListView, false));
//                            mContactsListView.setAdapter(mContactEntryAdapter);
//                            mContactEntryAdapter.notifyDataSetChanged();
//
//                        }

                        String filterText = getFilterText();
                        if (!TextUtils.isEmpty(filterText)) {
//                                                    if (mGroupID == null
//                                                            || mGroupID == GroupOperationActivity.DISPLAY_GROUP_BUTTON_ALLCONTACTS) {
//                                                        mListManager.setListFlag(Constants.SHOW_CONTACT_INFO);
//                                                    } else {
//                                                        mListManager.setListFlag(Constants.SHOW_GROUP_INFO);
//                                                    }
                            mContactEntryAdapter.setCurrentSearchText(filterText);
                            if (mListManager != null) {
                                mListManager.onRefresh(filterText, mIfShowPeopleNoPhone);
                            }
                        }
                    } else {

                        mNull.setVisibility(View.VISIBLE);

                    }


                    whileLock = false;
                    Constants.IS_START_UP = false;
                }
            }.execute();
        }
    }

    /**
     * 刷新ListView
     */
    public void freshContactsByStatus() {
        if (mListManager == null) {
            initListManager(getIntent());
        }
        switch (mListStatus) {
            case ENUM_SHOW_CONTACT_INFO: {
                if (mContactEntryAdapter != null) {
                    mContactsListView.setAdapter(mContactEntryAdapter);
                }
                mSortByProperty = Constants.ORDER_BY_NAME_INDEX;
                if (mSortByProperty == Constants.ORDER_BY_NAME_INDEX) {
                    mBackgroundQueryHandler.startQuery(Constants.DIALER_CONTACTS_QUERY_TOKEN, null,

                            ContactsContract.Contacts.CONTENT_URI, ContactsDBReader.CONTACTS_SUMMARY_PROJECTION,
                            mIfShowPeopleNoPhone ? null : Constants.CLAUSE_ONLY_PHONES, null,
                            " sort_key ASC"/*
                                                * the sort_key is a hide var in
                                                * framework
                                                */
                            // 姓名顺序
                    );
                } else if (mSortByProperty == Constants.ORDER_BY_CALL_LOG_INDEX) {
                    mBackgroundQueryHandler.startQuery(Constants.DIALER_CONTACTS_QUERY_TOKEN, null,

                            ContactsContract.Contacts.CONTENT_URI, ContactsDBReader.CONTACTS_SUMMARY_PROJECTION,
                            mIfShowPeopleNoPhone ? null : Constants.CLAUSE_ONLY_PHONES, null,
                            ContactsContract.Contacts.TIMES_CONTACTED + " DESC, sort_key ASC");
                    // 联系频率
                }

                mListManager.setListFlag(Constants.SHOW_CONTACT_INFO);
                break;
            }
        }
        //     isRefreshable();
        //mContactsListView.setCanRefreshable(false);

    }

    /**
     * 是否需要有下拉刷新
     */
    public void isRefreshable() {
        if (mListStatus == ListStatus.ENUM_SHOW_CLOUD_CONTACT) {
            //mContactsListView.setCanRefreshable(false);
        } else {
            //mContactsListView.setCanRefreshable(true);
        }
    }


    /**
     * 初始化List状态
     *
     * @param intent
     */
    private void initListStatus(Intent intent) {
        int showContent = Constants.SHOW_CONTACT_INFO;
        String action = intent.getAction();
        if ("cloud_contact_list".equals(intent.getAction()) || "set_structure_group_contact".equals(intent.getAction()) || "structure_tag_click".equals(intent.getAction()) || "manage_delete_member".equals(intent.getAction()) || "manage_add_manager".equals(intent.getAction()) || "cloud".equals(intent.getStringExtra("where"))) {
            mListStatus = CloudDialerActivity.ListStatus.ENUM_SHOW_CLOUD_CONTACT;
        } else {
            mListStatus = CloudDialerActivity.ListStatus.ENUM_SHOW_CONTACT_INFO;
        }
        mShowContent = showContent;
    }

    /**
     * 选择排序方式PopupWindow
     */
    private void orderContactsWindow() {
        View mainView = mLayoutInflater.inflate(R.layout.order_contacts_activity, null);
        mOrderContactsWin = new PopupWindow(this);
        mOrderContactsWin.setBackgroundDrawable(new BitmapDrawable());
        mOrderContactsWin.setFocusable(true);
        mOrderContactsWin.setTouchable(true);
        mOrderContactsWin.setOutsideTouchable(true); // 设置非PopupWindow区域可触摸
        mOrderContactsWin.setContentView(mainView);
        mOrderContactsWin.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        mOrderContactsWin.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        mOrderContactsWin.setAnimationStyle(R.style.bottomStyle);
        ImageView fre_image = (ImageView) mainView.findViewById(R.id.image_frequency_select);
        ImageView name_image = (ImageView) mainView.findViewById(R.id.image_name_select);
        int type = PreferenceUtil.getInstance(this).getInt(PreferenceUtil.CONTACT_NAME_SORT, Constants.ORDER_BY_CALL_LOG_INDEX);
        if (type == Constants.ORDER_BY_CALL_LOG_INDEX) {
            fre_image.setVisibility(View.VISIBLE);
            name_image.setVisibility(View.GONE);
        } else if (type == Constants.ORDER_BY_NAME_INDEX) {
            fre_image.setVisibility(View.GONE);
            name_image.setVisibility(View.VISIBLE);
        }
        LinearLayout orderByName = (LinearLayout) mainView.findViewById(R.id.order_by_name);
        LinearLayout orderByFre = (LinearLayout) mainView.findViewById(R.id.order_by_frequency);
        Button cancel = (Button) mainView.findViewById(R.id.order_cancel);
        orderByName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOrderContactsWin.dismiss();
                PreferenceUtil.getInstance(CloudDialerActivity.this).save(PreferenceUtil.CONTACT_NAME_SORT, Constants.ORDER_BY_NAME_INDEX);
                mSortByProperty = Constants.ORDER_BY_NAME_INDEX;
                freshContactsByStatus();
            }
        });

        orderByFre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOrderContactsWin.dismiss();
                PreferenceUtil.getInstance(CloudDialerActivity.this).save(PreferenceUtil.CONTACT_NAME_SORT, Constants.ORDER_BY_CALL_LOG_INDEX);
                mSortByProperty = Constants.ORDER_BY_CALL_LOG_INDEX;
                mSortByProperty = Constants.ORDER_BY_NAME_INDEX;
                freshContactsByStatus();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOrderContactsWin.dismiss();
            }
        });
        mOrderContactsWin.showAtLocation(mKeyBoardMainContainer, Gravity.BOTTOM, 0, 0);
        mOrderContactsWin.update();

    }

    public void changeResultGroup(final LinkedHashSet<Long> allContactId) {

        ArrayList<CloudContact> contacts = new ArrayList<CloudContact>();
        for (CloudContact contact : rootcontactList) {
            Long id = (Long) Long.valueOf(contact.contactId);
            if (allContactId.contains(id)) {
                contacts.add(contact);
            }
        }

        updateCloudContactList(contacts);

    }

    /**
     * 更新结果
     *
     * @param allContactId
     */
    public void changeResult(final LinkedHashSet<Long> allContactId) {
        Pair<String, List<Long>> sectionPair = null;// new Pair<String,
        // ArrayList<Long>>();
        List<Pair<String, List<Long>>> result = new ArrayList<Pair<String, List<Long>>>();
        // mAllContactId.clear();
        // mAllContactId.addAll(allContactId);

        if (allContactId == null || allContactId.size() == 0) {
            this.mNull.setVisibility(View.VISIBLE);
        } else {
            this.mNull.setVisibility(View.GONE);
        }


        if (PinyinSearch.mHaveNewInput) {
            return;
        }
        mSortByProperty = Constants.ORDER_BY_NAME_INDEX;
        if (mSortByProperty == Constants.ORDER_BY_NAME_INDEX) {
            ArrayList<Long> contactIds = new ArrayList<Long>(allContactId.size());
            Iterator<Long> it = allContactId.iterator();
            while (it.hasNext()) {
                long contactId = it.next();
                if (
//                        (mDisplayCallLog && !(mListStatus == ListStatus.ENUM_SHOW_LAST_NAME_GROUP || mListStatus == ListStatus.ENUM_SHOW_CITY_GROUP))
//
//                        ||
                        mAllContactId.contains(contactId)) {
                    contactIds.add(contactId);
                }
            }

            MyCompartor mc = new MyCompartor();
            Collections.sort(contactIds, mc);


            if (PinyinSearch.mHaveNewInput) {
                return;
            }


            String sectionText = getSections()[0] + "(" + allContactId.size() + ")";
            sectionPair = new Pair<String, List<Long>>(sectionText, contactIds);
            result.add(sectionPair);
        } else if (mSortByProperty == Constants.ORDER_BY_CALL_LOG_INDEX) {
            Iterator<Long> it = allContactId.iterator();
            ArrayList<Long> contactedList = new ArrayList<Long>();
            ArrayList<Long> noContactedList = new ArrayList<Long>();

            while (it.hasNext()) {

                if (PinyinSearch.mHaveNewInput) {
                    return;
                }
                long contactId = it.next();
                if (!mAllContactId.contains(contactId)) {
                    continue;
                }
                // ContactInPersist persist = (ContactInPersist)
                // mPreferenceUtil.getObject(Long.toString(contactId));
                if (mPinyinSearch == null) {
                    mPinyinSearch = PinyinSearch.getInstance(this.getApplicationContext());
                }
                ContactInfoNode memoryNode = mPinyinSearch.getContactInfo().get(contactId);
                long contactedNumber = -1;
                if (memoryNode == null) {
                    contactedNumber = ContactsDBReader.getContactedNumber(contactId,
                            this.getContentResolver());
                } else {
                    contactedNumber = memoryNode.contactedNumber;
                }

                if (contactedNumber > 0) {
                    contactedList.add(contactId);
                } else {
                    noContactedList.add(contactId);

                }
            }
            String sectionText = getSections()[0] + "(" + contactedList.size() + ")";
            sectionPair = new Pair<String, List<Long>>(sectionText, contactedList);
            result.add(sectionPair);

            sectionText = getSections()[1] + "(" + noContactedList.size() + ")";
            sectionPair = new Pair<String, List<Long>>(sectionText, noContactedList);
            result.add(sectionPair);

        } /*
               * else if (mSortByProperty == Constants.ORDER_BY_CREATE_TIME_INDEX) {
               * //代码不要删除 Iterator<Long> it = allContactId.iterator(); Date now =
               * Calendar.getInstance().getTime(); HashMap<Integer, List<Long>>
               * sectionMap = new HashMap<Integer, List<Long>>(); while
               * (it.hasNext()) { long contactId = it.next(); // ContactInPersist
               * persist = (ContactInPersist)
               * mPreferenceUtil.getObject(Long.toString(contactId));
               * ContactInfoNode memoryNode =
               * PinyinSearch.getInstance().getContactInfo().get(contactId); String
               * creationTime = null; if (memoryNode == null ||
               * StringUtil.isEmpty(memoryNode.creationTime)) { // contactedNumber =
               * ContactsDBReader.getContactedNumber(contactId,
               * this.getContentResolver()); // creationTime =
               * ContactsDBReader.getCreationTimeByContactId
               * (this.getContentResolver(), contactId); creationTime =
               * StringUtil.getStringDate(); } else { creationTime =
               * memoryNode.creationTime; } if (!StringUtil.isEmpty(creationTime)) {
               * SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); Date
               * createDate = null; try { createDate = df.parse(creationTime); }
               * catch (ParseException e) { e.printStackTrace(); } Integer
               * differenceType = StringUtil.calculateSectionByTime(now,
               * createDate); if (sectionMap.containsKey(differenceType)) {
               * sectionMap.get(differenceType).add(contactId); } else { List<Long>
               * contactIdList = new ArrayList<Long>();
               * contactIdList.add(contactId); sectionMap.put(differenceType,
               * contactIdList); } } } Iterator<Integer> sectionIt =
               * sectionMap.keySet().iterator(); while (sectionIt.hasNext()) {
               * Integer section = sectionIt.next(); String sectionText =
               * getSections()[section] + "("+ sectionMap.get(section).size() + ")";
               * sectionPair = new Pair<String, List<Long>>(sectionText,
               * sectionMap.get(section)); result.add(sectionPair); } }
               */

        // mContactEntryAdapter = new ContactEntryAdapter(mLayoutInflater, this,
        // result);
        if (PinyinSearch.mHaveNewInput) {
            return;
        }

        mContactEntryAdapter.changeContent(result);
        mContactEntryAdapter.setInterrupted(false);
        //mContactsListView.setPinnedHeaderView(mLayoutInflater.inflate(
        //R.layout.item_composer_header, mContactsListView, false));
        mContactsListView.setAdapter(mContactEntryAdapter);
    }


    public static final String[] RAW_PROJECTION = new String[]{
            ContactsContract.Data.RAW_CONTACT_ID, ContactsContract.Data.CONTACT_ID, ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID
    };

    // 根据分组查询联系人的selection
    public static final String RAW_CONTACTS_WHERE = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=?" + " and "
            + ContactsContract.Data.MIMETYPE + "=" + "'" + ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";

    //创建号码群联系人
    public void addContactToGroupDirect(long groupid) {
        mListStatus = ListStatus.ENUM_SHOW_CONTACT_INFO;
        freshContactsByStatus();
        batchOperation(Constants.BATCH_OPERATION_CLOUD_UPLOAD);
        mCloudGid = groupid;
    }


    public void batchOperation(int resultCode) {

        mTitleBarSelectMode.setVisibility(View.VISIBLE);
        mTitleBarNormalMode.setVisibility(View.GONE);

        mBatchOpertionLayout.setVisibility(View.VISIBLE);
        if (mListStatus == ListStatus.ENUM_SHOW_CONTACT_INFO) {
            mBatchOperitonTitle.setText("本地通讯录");
        } else {
            mBatchOperitonTitle.setText(/*tagName*/groupName);
        }
        if (resultCode == Constants.BATCH_OPERATION_CLOUD_UPLOAD || resultCode == Constants.BATCH_OPERATION_INVITE_MANAGER || resultCode == Constants.BATCH_OPERATION_ADD_LOCAL_CHAT_MEMBER) {
            enterBatchOperation(resultCode, false);
        } else if (resultCode == Constants.BATCH_OPERATION_ADD_CLOUD_CHAT_MEMBER) {
            enterBatchOperation(resultCode, true);
        } else if (resultCode == Constants.BATCH_OPERATION_ADD_GROUP_MEMBER) {
            mIsAddGroupMember = true;
            enterBatchOperation(resultCode, true);
        } else if (resultCode == Constants.BATCH_OPERATION_MANAGER_ADD) {
            enterBatchOperation(resultCode, true);
        } else if (resultCode == Constants.BATCH_OPERATION_MEMBER_DELETE) {
            enterBatchOperation(resultCode, true);
        } else if (resultCode == Constants.CHECKBOX_STATUS_BUSINESSCARD_WITHSMS) {
            enterBatchOperation(resultCode, true);
        } else if (resultCode == Constants.BATCH_OPERATION_EVENT_ADD_RECEIVER) {
            enterBatchOperation(resultCode, true);
        } else if (resultCode == Constants.BATCH_OPERATION_EVENT_ADD_LOCAL_RECEIVER) {
            enterBatchOperation(resultCode, true);
        } else if (resultCode == Constants.BATCH_OPERATION_SCHEDULE_MANAGER) {
            enterBatchOperation(resultCode, true);
        } else if (resultCode == Constants.BATCH_OPERATION_ATTENDANCE_MEMBER) {
            enterBatchOperation(resultCode, true);
        } else if (resultCode == Constants.BATCH_OPERATION_APPROVAL_LEADER) {
            enterBatchOperation(resultCode, true);
        } else if (resultCode == Constants.BATCH_OPERATION_WEEKLY_MANAGER) {
            enterBatchOperation(resultCode, true);
        }
    }


    public void enterBatchOperation(int batchType, boolean clear) {
        updateSelectTitleSkin();

        mIfBatchOperation = true;
        mBatchOperationType |= (1 << batchType);
        if (batchType == Constants.BATCH_OPERATION_ADD_LOCAL_CHAT_MEMBER || batchType == Constants.BATCH_OPERATION_EVENT_ADD_LOCAL_RECEIVER || batchType == Constants.BATCH_OPERATION_EVENT_ADD_RECEIVER) {
            mBtnSend.setText(getString(R.string.batch_operation_complete));
            mContactEntryAdapter.setLocalContactCheckStyle(true);
        } else if (batchType == Constants.BATCH_OPERATION_CLOUD_UPLOAD) {
            mBtnSend.setText(getString(R.string.batch_operation_upload));
        } else if (batchType == Constants.BATCH_OPERATION_INVITE_MANAGER) {
            mBtnSend.setText(getString(R.string.invite));
        } else if (batchType == Constants.BATCH_OPERATION_ADD_CLOUD_CHAT_MEMBER || batchType == Constants.BATCH_OPERATION_ADD_GROUP_MEMBER || batchType == Constants.BATCH_OPERATION_MANAGER_ADD || batchType == Constants.BATCH_OPERATION_SCHEDULE_MANAGER || batchType == Constants.BATCH_OPERATION_ATTENDANCE_MEMBER || batchType == Constants.BATCH_OPERATION_APPROVAL_LEADER || batchType == Constants.BATCH_OPERATION_WEEKLY_MANAGER) {
            mBtnSend.setText(R.string.batch_operation_complete);
            //mTabContactGroup.setText(tagName);
        } else if (batchType == Constants.BATCH_OPERATION_MEMBER_DELETE) {
            mBtnSend.setText(R.string.batch_operation_delete);
            //mTabContactGroup.setText("删除" + groupName + "号码簿管理员");
        } else if (batchType == Constants.CHECKBOX_STATUS_BUSINESSCARD_WITHSMS) {
            mBtnSend.setText(R.string.batch_operation_send);
        } else {
            mBtnSend.setText(R.string.batch_operation_complete);
        }
        //        setAddContactAble(false);
        if (batchType == Constants.BATCH_OPERATION_ADD_CLOUD_CHAT_MEMBER || batchType == Constants.BATCH_OPERATION_EVENT_ADD_RECEIVER) {
            if (clear) {
                mCloudContactAdapter.setIfCheckBoxShow(true);
                if (batchType == Constants.BATCH_OPERATION_ADD_CLOUD_CHAT_MEMBER) {
                    mCloudContactAdapter.setCloudContactCheckStyle(true);
                } else {
                    mCloudContactAdapter.setCloudContactCheckStyle(false);
                }
                mContactsListView.setAdapter(mCloudContactAdapter);
                mCloudContactAdapter.notifyDataSetChanged();
            }
        } else if (batchType == Constants.BATCH_OPERATION_ADD_GROUP_MEMBER) {
            if (clear) {
                mCloudContactAdapter.setIfCheckBoxShow(true, chatContacts);
                mContactsListView.setAdapter(mCloudContactAdapter);
                mCloudContactAdapter.notifyDataSetChanged();
            }
        } else if (batchType == Constants.BATCH_OPERATION_MANAGER_ADD) {
            if (clear) {
                mCloudContactAdapter.setIfCheckBoxShow(true);
                mCloudContactAdapter.setCloudContactCheckStyle(true);
                mContactsListView.setAdapter(mCloudContactAdapter);
                mCloudContactAdapter.notifyDataSetChanged();
            }
        } else if (batchType == Constants.BATCH_OPERATION_MEMBER_DELETE) {
            if (clear) {
                mCloudContactAdapter.setIfCheckBoxShow(true);
                mContactsListView.setAdapter(mCloudContactAdapter);
                mCloudContactAdapter.notifyDataSetChanged();
            }
        } else if (batchType == Constants.CHECKBOX_STATUS_BUSINESSCARD_WITHSMS) {
            if (clear) {
                mContactEntryAdapter.setIfCheckBoxShow(true);
            } else {
                mContactEntryAdapter.setIfCheckBoxShowNoClear(true);
            }
            mContactsListView.setAdapter(mContactEntryAdapter);
            mContactEntryAdapter.notifyDataSetChanged();

        } else if (batchType == Constants.BATCH_OPERATION_SCHEDULE_MANAGER) {
            if (clear) {
                mCloudContactAdapter.setIfCheckBoxShow(true);
                mCloudContactAdapter.setCloudContactCheckStyle(true);
                mContactsListView.setAdapter(mCloudContactAdapter);
                mCloudContactAdapter.notifyDataSetChanged();
            }
        } else if (batchType == Constants.BATCH_OPERATION_ATTENDANCE_MEMBER) {
            if (clear) {
                mCloudContactAdapter.setIfCheckBoxShow(true);
                mCloudContactAdapter.setCloudContactCheckStyle(false);
                mContactsListView.setAdapter(mCloudContactAdapter);
                mCloudContactAdapter.notifyDataSetChanged();
            }
        } else if (batchType == Constants.BATCH_OPERATION_APPROVAL_LEADER) {
            if (clear) {
                mCloudContactAdapter.setIfCheckBoxShow(true);
                mCloudContactAdapter.setCloudContactCheckStyle(true);
                mContactsListView.setAdapter(mCloudContactAdapter);
                mCloudContactAdapter.notifyDataSetChanged();
            }
        } else if (batchType == Constants.BATCH_OPERATION_WEEKLY_MANAGER) {
            if (clear) {
                mCloudContactAdapter.setIfCheckBoxShow(true);
                mCloudContactAdapter.setCloudContactCheckStyle(true);
                mContactsListView.setAdapter(mCloudContactAdapter);
                mCloudContactAdapter.notifyDataSetChanged();
            }
        } else {
            if (clear) {
                mContactEntryAdapter.setIfCheckBoxShow(true);
            } else {
                mContactEntryAdapter.setIfCheckBoxShowNoClear(true);
            }
        }
    }

    public void quitBatchOperation(boolean clear, boolean clearBtn) {
        mShowModleChiceView.backToDefaultState();//已选全选按钮恢复到默认状态
        mLayoutSelectAll.setVisibility(View.VISIBLE);
        mCbSelectAll.setChecked(false);
        mBatchOpertionLayout.setVisibility(View.GONE);
        if (mListStatus == ListStatus.ENUM_SHOW_CONTACT_INFO) {
            mContactEntryAdapter.changeToAllContent();
            if (mContactEntryAdapter.mBackAllContactsIdBySection != null) {
                mContactEntryAdapter.mBackAllContactsIdBySection.clear();
            }
            if (mContactEntryAdapter.mSelectedContactsIdBySection != null) {
                mContactEntryAdapter.mSelectedContactsIdBySection.clear();
            }
        } else {
            if (mCloudContactAdapter != null) {
                mCloudContactAdapter.changeToAllContent();
                if (mCloudContactAdapter.mBackUpContactList != null) {
                    mCloudContactAdapter.mBackUpContactList.clear();
                }
                if (mCloudContactAdapter.mSelectedContactList != null && mCloudContactAdapter.mSelectedContactList.size() > 0) {
                    mCloudContactAdapter.mSelectedContactList.clear();
                }
            }
        }
        if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_CLOUD_CHAT_MEMBER) != 0) {
            mCloudContactAdapter.clearSelected();
            mCloudContactAdapter.setIfCheckBoxShow(false);
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_LOCAL_CHAT_MEMBER) != 0) {
            mContactEntryAdapter.clearSelected();
            mContactEntryAdapter.setIfCheckBoxShow(false);
            mContactsListView.setAdapter(mContactEntryAdapter);
        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_EVENT_ADD_RECEIVER) != 0) {
            mCloudContactAdapter.clearSelected();
            mCloudContactAdapter.setIfCheckBoxShow(false);
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), tagId, contactId);
        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_EVENT_ADD_LOCAL_RECEIVER) != 0) {
            mContactEntryAdapter.clearSelected();
            mContactEntryAdapter.setIfCheckBoxShow(false);
            mContactsListView.setAdapter(mContactEntryAdapter);
        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ADD_GROUP_MEMBER) != 0) {
            mIsAddGroupMember = false;
            mCloudContactAdapter.clearSelected();
            mCloudContactAdapter.setIfCheckBoxShow(false);
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);
        } else if ((mBatchOperationType & 1 << Constants.CHECKBOX_STATUS_BUSINESSCARD_WITHSMS) != 0) {
            mContactEntryAdapter.clearSelected();
            mContactEntryAdapter.setIfCheckBoxShow(false);
            mContactsListView.setAdapter(mContactEntryAdapter);
        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_MANAGER_ADD) != 0) {
            mCloudContactAdapter.clearSelected();
            mCloudContactAdapter.setIfCheckBoxShow(false);
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);
        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_MEMBER_DELETE) != 0) {
            mCloudContactAdapter.clearSelected();
            mCloudContactAdapter.setIfCheckBoxShow(false);
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);
        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_SCHEDULE_MANAGER) != 0) {
            mCloudContactAdapter.clearSelected();
            mCloudContactAdapter.setIfCheckBoxShow(false);
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);
        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_ATTENDANCE_MEMBER) != 0) {
            mCloudContactAdapter.clearSelected();
            mCloudContactAdapter.setIfCheckBoxShow(false);
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);
        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_APPROVAL_LEADER) != 0) {
            mCloudContactAdapter.clearSelected();
            mCloudContactAdapter.setIfCheckBoxShow(false);
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);
        } else if ((mBatchOperationType & 1 << Constants.BATCH_OPERATION_WEEKLY_MANAGER) != 0) { // 周报查看
            mCloudContactAdapter.clearSelected();
            mCloudContactAdapter.setIfCheckBoxShow(false);
            getCloudContactList(groupId, mCurrentPage, mCloudHandler.obtainMessage(MSG_CONTACT_GETLIST), "", contactId);
        }


        // set status
        if (clearBtn) {
            setSelectImage(false);
            mTitleBarSelectMode.setVisibility(View.GONE);
            mTitleBarNormalMode.setVisibility(View.VISIBLE);

            //isShowChange=true;

        }
        //mTabContactGroup.setClickable(true);
        //        dmg.setCanFling(true);
        mIfBatchOperation = false;

        if (clear) {
            mBatchOperationType = 0;
        }
        // set text
        // set list status
        // mContactsListAdapter.removeAllSelContacts();
        // mContactsListAdapter.setmBulkSmsState(false);
        if (mContactEntryAdapter != null) {
            if (clear) {
                mContactEntryAdapter.setIfCheckBoxShow(false);
            } else {
                mContactEntryAdapter.setIfCheckBoxShowNoClear(false);
            }
        }

        mContactEntryAdapter.notifyDataSetChanged();
        setAddContactAble(true);
        removeFullScreen();
    }

    public void setAddContactAble(boolean able) {
        if (mKeyboardVertFrag != null) {
            if (mKeyboardVertFrag.mChangeDialPadT9_vertical_right != null) {
                mKeyboardVertFrag.mChangeDialPadT9_vertical_right.setClickable(able);
                mKeyboardVertFrag.mChangeDialPadT9_vertical_right.setEnabled(able);
            }
            if (mKeyboardVertFrag.mChangeDialPadT9_vertical_left != null) {
                mKeyboardVertFrag.mChangeDialPadT9_vertical_left.setClickable(able);
                mKeyboardVertFrag.mChangeDialPadT9_vertical_left.setEnabled(able);
            }
            if (mKeyboardVertFrag.mChangeDialPadAllWord_vertical_left != null) {
                mKeyboardVertFrag.mChangeDialPadAllWord_vertical_left.setClickable(able);
                mKeyboardVertFrag.mChangeDialPadAllWord_vertical_left.setEnabled(able);
            }
            if (mKeyboardVertFrag.mChangeDialPadAllWord_vertical_right != null) {
                mKeyboardVertFrag.mChangeDialPadAllWord_vertical_right.setClickable(able);
                mKeyboardVertFrag.mChangeDialPadAllWord_vertical_right.setEnabled(able);
            }
        }
        if (mKeyboardHoriFrag != null) {
            if (mKeyboardHoriFrag.mDisplayUnderPanelButton != null) {
                mKeyboardHoriFrag.mDisplayUnderPanelButton.setClickable(able);
                mKeyboardHoriFrag.mDisplayUnderPanelButton.setEnabled(able);
            }
        }
    }

    public void removeFullScreen() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setAttributes(attrs);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        if (mainTitle != null) {
            mainTitle.setVisibility(View.GONE);
        }
    }

    public void setFullScreen(String text) {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        mainTitle = (TextView) findViewById(R.id.main_title_text);
        mainTitle.setText(text);
        mainTitle.setVisibility(View.VISIBLE);
    }

    public void clearCheckboxStatus() {
        mContactEntryAdapter.setIfCheckBoxShow(false);
        mContactEntryAdapter.notifyDataSetChanged();
    }

    private void uploadCloudContact(final ArrayList<Long> contactIdList) {
        final int totalSize = contactIdList.size();
        new AsyncTask<Void, Integer, Void>() {
            public Void doInBackground(Void... params) {
                JSONArray jNameCardList = new JSONArray();
                for (int i = 0; i < totalSize; i++) {
                    NameCardUtil.contact2JsonCloudUpload(contactIdList.get(i), jNameCardList,
                            CloudDialerActivity.this);
                }
                addContactList(StringUtil.compressByGzip(jNameCardList.toString()), totalSize);
                return null;
            }

        }.execute();
    }

    /**
     * upload jsonArray format contacts
     *
     * @param contactListStr
     */
    private void addContactList(String contactListStr, int totalSize) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, String.valueOf(mCloudGid)));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACTS_LIST, contactListStr));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACTS_NUM, totalSize + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TAG_ID, tagId));
        AddContactListMsg addContactList = new AddContactListMsg(
                mCloudHandler.obtainMessage(MSG_CONTACT_ADDLIST), totalSize);
        addContactList.mApi = AsynHttpClient.API_CONTACT_ADDLIST;
        addContactList.mParams = nvps;
        AsynHttpClient.getInstance(this).execCcHttp(addContactList);
    }

    //设置节点下联系人
    private void setGroupContact(String contactIds) {
        GetMsgHttpReceiver getMsg = new GetMsgHttpReceiver(mCloudHandler.obtainMessage(MSG_SET_CONTACT));
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_TAG_ID, tagId));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACT_IDS, contactIds));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_TAG_PATH, tagPath));
        getMsg.mApi = AsynHttpClient.API_TAGS_SET;
        getMsg.mParams = params;
        AsynHttpClient.getInstance(this).execCcHttp(getMsg);
    }


    //添加管理员
    private void setGroupManager(String contactIds) {
        SetManagerHttpReceiver getMsg = new SetManagerHttpReceiver(mCloudHandler.obtainMessage(MSG_GROUP_MANAGER));
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, groupId));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACT_IDS, contactIds));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACT_ID, contactId));
        getMsg.mApi = AsynHttpClient.API_GROUP_ADD_MANAGER;
        getMsg.mParams = params;
        AsynHttpClient.getInstance(this).execCcHttp(getMsg);
    }

    //批量删除号码圈成员
    private void deleteGroupMember(String contactIds) {
        GetMsgHttpReceiver getMsg = new GetMsgHttpReceiver(mCloudHandler.obtainMessage(MSG_GROUP_DELETE_MEMBER));
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, groupId));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACT_IDS, contactIds));
        getMsg.mApi = AsynHttpClient.API_GROUP_DELUSERS;
        getMsg.mParams = params;
        AsynHttpClient.getInstance(this).execCcHttp(getMsg);
    }

    //批量删除号码圈成员
    private void addReceiverToEvent(String eventReceiver) {
        GetMsgHttpReceiver getMsg = new GetMsgHttpReceiver(mCloudHandler.obtainMessage(MSG_ADD_RECEIVER_TO_EVENT));
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ID, eventId));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TYPE, eventTypeId));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_MEMBERS, eventReceiver));
        getMsg.mApi = AsynHttpClient.API_EVENT_ADD_MEMBERS;
        getMsg.mParams = params;
        AsynHttpClient.getInstance(this).execEventHttp(getMsg);
    }

    @Override
    protected void onResume() {
        super.onResume();
        /*
        // TODO 默认搜索框内没有搜索字
        setFilterText("");
        if (mPinyinSearch == null) {
            mPinyinSearch = PinyinSearch.getInstance(this.getApplicationContext());
        }
        if (mBatchOperationType == 0) {
            quitBatchOperation(true, true);
            freshContactsByStatus();
            if (mCloudContactAdapter != null) {
                mCloudContactAdapter.clearSelected();
                mCloudContactAdapter.setIfCheckBoxShow(false);
            }
        }
        if (mIsLoad) {
            initIntentData();
        }
        */

        /*if (this.mCloudContactAdapter != null) {
            this.mCloudContactAdapter.selectedId = null;
            this.mCloudContactAdapter.notifyDataSetChanged();
        }
        if (this.mContactEntryAdapter != null) {
            this.mContactEntryAdapter.clearSelectedStatus();
        }*/


    }

    @Override
    protected void onPause() {
        super.onPause();
        if (LocalLogin.getInstance().isLogedin()) {
            mPreferenceUtil.unregisterCloudContactListener(this);
        }
        isSingleChoose = false;
    }

    @Override
    protected void onDestroy() {
/*
        if(this.mVertySkin!=null){
        this.mVertySkin=null;
        }
*/
    /*   
    if(this.mHorizSkin!=null){
        this.mHorizSkin=null;
        }
*/
        if (player != null) {
            player.destory();
            player = null;
        }
        super.onDestroy();
    }


    /**
     * 添加日程表管理员
     *
     * @param users
     */
    private void addScheduleManager(String users) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MANAGERS, users));
        Message message = mCloudHandler.obtainMessage(MSG_SCHEDULE_ADD_MANAGER);
        WithoutObjMsg getMsg = new WithoutObjMsg(message);
        message.obj = "schedule_manager";
        getMsg.mApi = AsynHttpClient.API_EVENT_CALENDAR_ADD_MANAGERS;
        getMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(getMsg);
    }

    /**
     * 添加审批管理员
     *
     * @param users
     */
    private void addApprovalManager(String users) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, groupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CURRENT_CONTACT_ID, contactId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACT_IDS, users));
        Message message = mCloudHandler.obtainMessage(MSG_SCHEDULE_ADD_MANAGER);
        WithoutObjMsg getMsg = new WithoutObjMsg(message);
        message.obj = "approval_leader_add";
        getMsg.mApi = AsynHttpClient.API_APPROVAL_MAMAGER_ADD;
        getMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execCcHttp(getMsg);
    }

    /**
     * 添加周报查看人
     *
     * @param users
     */
    private void addWeeklyManager(String users) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, groupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_REVIEWERS, users));
        Message message = mCloudHandler.obtainMessage(MSG_WEEKLY_ADD_MANAGER);
        WithoutObjMsg getMsg = new WithoutObjMsg(message);
        message.obj = "weekly_manager";
        getMsg.mApi = AsynHttpClient.API_EVENT_WEEKLY_PERMISSION_USER_ADD;
        getMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(getMsg);
    }


    /**
     * 解决横竖屏切换的bug
     *
     * @param newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // land donothing is ok
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            // port donothing is ok
        }
    }
}